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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.771   ! raeburn     4: # $Id: grades.pm,v 1.770 2020/05/20 22:02:57 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;
                   1592:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1593:     if (cleantxt=="") {
1.736     damieng  1594: 	alert("$js_lt{'plse'}");
1.44      ng       1595: 	return;
                   1596:     }
1.736     damieng  1597:     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1598:     if (nret==null) return;
1.127     ng       1599:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1600:     if (document.SCORE.keywords.value != "") {
1.127     ng       1601: 	document.SCORE.refresh.value = "on";
1.44      ng       1602: 	document.SCORE.submit();
                   1603:     }
                   1604:     return;
                   1605:   }
                   1606: 
                   1607: //====================== Script for composing message ==============
1.80      ng       1608:    // preload images
                   1609:    img1 = new Image();
                   1610:    img1.src = "$iconpath/mailbkgrd.gif";
                   1611:    img2 = new Image();
                   1612:    img2.src = "$iconpath/mailto.gif";
                   1613: 
1.44      ng       1614:   function msgCenter(msgform,usrctr,fullname) {
                   1615:     var Nmsg  = msgform.savemsgN.value;
                   1616:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1617:     var subject = msgform.msgsub.value;
1.127     ng       1618:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1619:     re = /msgsub/;
                   1620:     var shwsel = "";
                   1621:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1622:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1623:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1624:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1625: 	var testmsg = "savemsg"+i+",";
                   1626: 	re = new RegExp(testmsg,"g");
1.44      ng       1627: 	shwsel = "";
                   1628: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1629: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1630: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1631: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1632: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1633:     }
1.125     ng       1634:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1635:     shwsel = "";
                   1636:     re = /newmsg/;
                   1637:     if (re.test(msgchk)) { shwsel = "checked" }
                   1638:     newMsg(newmsg,shwsel);
                   1639:     msgTail(); 
                   1640:     return;
                   1641:   }
                   1642: 
1.123     ng       1643:   function checkEntities(strx) {
                   1644:     if (strx.length == 0) return strx;
                   1645:     var orgStr = ["&", "<", ">", '"']; 
                   1646:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1647:     var counter = 0;
                   1648:     while (counter < 4) {
                   1649: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1650: 	counter++;
                   1651:     }
                   1652:     return strx;
                   1653:   }
                   1654: 
                   1655:   function strReplace(strx, orgStr, newStr) {
                   1656:     return strx.split(orgStr).join(newStr);
                   1657:   }
                   1658: 
1.44      ng       1659:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1660:     var height = 70*Nmsg+250;
1.44      ng       1661:     if (height > 600) {
                   1662: 	height = 600;
                   1663:     }
1.118     ng       1664:     var xpos = (screen.width-600)/2;
                   1665:     xpos = (xpos < 0) ? '0' : xpos;
                   1666:     var ypos = (screen.height-height)/2-30;
                   1667:     ypos = (ypos < 0) ? '0' : ypos;
                   1668: 
1.668     www      1669:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1670:     pWin.focus();
                   1671:     pDoc = pWin.document;
1.219     www      1672:     pDoc.$docopen;
1.351     albertel 1673:     pDoc.write('$start_page_msg_central');
1.76      ng       1674: 
                   1675:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1676:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1677:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1678: 
1.676     golterma 1679:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1680:     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       1681: }
                   1682:     function displaySubject(msg,shwsel) {
1.76      ng       1683:     pDoc = pWin.document;
1.676     golterma 1684:     pDoc.write("<tr>");
                   1685:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1686:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1687:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1688: }
                   1689: 
1.72      ng       1690:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1691:     pDoc = pWin.document;
1.676     golterma 1692:     pDoc.write("<tr>");
                   1693:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1694:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1695:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1696: }
                   1697: 
                   1698:   function newMsg(newmsg,shwsel) {
1.76      ng       1699:     pDoc = pWin.document;
1.676     golterma 1700:     pDoc.write("<tr>");
                   1701:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1702:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1703:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1704: }
                   1705: 
                   1706:   function msgTail() {
1.76      ng       1707:     pDoc = pWin.document;
1.676     golterma 1708:     //pDoc.write("<\\/table>");
1.465     albertel 1709:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1710:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1711:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1712:     pDoc.write("<\\/form>");
1.351     albertel 1713:     pDoc.write('$end_page_msg_central');
1.128     ng       1714:     pDoc.close();
1.44      ng       1715: }
                   1716: 
                   1717: //====================== Script for keyword highlight options ==============
                   1718:   function kwhighlight() {
                   1719:     var kwclr    = document.SCORE.kwclr.value;
                   1720:     var kwsize   = document.SCORE.kwsize.value;
                   1721:     var kwstyle  = document.SCORE.kwstyle.value;
                   1722:     var redsel = "";
                   1723:     var grnsel = "";
                   1724:     var blusel = "";
1.736     damieng  1725:     var txtcol1 = "$js_lt{'col1'}";
                   1726:     var txtcol2 = "$js_lt{'col2'}";
                   1727:     var txtcol3 = "$js_lt{'col3'}";
                   1728:     var txtsiz1 = "$js_lt{'siz1'}";
                   1729:     var txtsiz2 = "$js_lt{'siz2'}";
                   1730:     var txtsiz3 = "$js_lt{'siz3'}";
                   1731:     var txtsty1 = "$js_lt{'sty1'}";
                   1732:     var txtsty2 = "$js_lt{'sty2'}";
                   1733:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1734:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1735:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1736:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1737:     var sznsel = "";
                   1738:     var sz1sel = "";
                   1739:     var sz2sel = "";
1.718     bisitz   1740:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1741:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1742:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1743:     var synsel = "";
                   1744:     var syisel = "";
                   1745:     var sybsel = "";
1.718     bisitz   1746:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1747:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1748:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1749:     highlightCentral();
1.718     bisitz   1750:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1751:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1752:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1753:     highlightend();
                   1754:     return;
                   1755:   }
                   1756: 
                   1757:   function highlightCentral() {
1.76      ng       1758: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1759:     var xpos = (screen.width-400)/2;
                   1760:     xpos = (xpos < 0) ? '0' : xpos;
                   1761:     var ypos = (screen.height-330)/2-30;
                   1762:     ypos = (ypos < 0) ? '0' : ypos;
                   1763: 
1.206     albertel 1764:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1765:     hwdWin.focus();
                   1766:     var hDoc = hwdWin.document;
1.219     www      1767:     hDoc.$docopen;
1.351     albertel 1768:     hDoc.write('$start_page_highlight_central');
1.76      ng       1769:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1770:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1771: 
1.718     bisitz   1772:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1773:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1774:   }
                   1775: 
                   1776:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1777:     var hDoc = hwdWin.document;
1.718     bisitz   1778:     hDoc.write("<tr>");
1.76      ng       1779:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1780:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1781:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1782:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1783:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1784:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1785:     hDoc.write("<\\/tr>");
1.44      ng       1786:   }
                   1787: 
                   1788:   function highlightend() { 
1.76      ng       1789:     var hDoc = hwdWin.document;
1.718     bisitz   1790:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1791:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1792:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1793:     hDoc.write("<\\/form>");
1.351     albertel 1794:     hDoc.write('$end_page_highlight_central');
1.128     ng       1795:     hDoc.close();
1.44      ng       1796:   }
                   1797: 
                   1798: SUBJAVASCRIPT
                   1799: }
                   1800: 
1.349     albertel 1801: sub get_increment {
1.348     bowersj2 1802:     my $increment = $env{'form.increment'};
                   1803:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1804:         $increment != .1) {
                   1805:         $increment = 1;
                   1806:     }
                   1807:     return $increment;
                   1808: }
                   1809: 
1.585     bisitz   1810: sub gradeBox_start {
                   1811:     return (
                   1812:         &Apache::loncommon::start_data_table()
                   1813:        .&Apache::loncommon::start_data_table_header_row()
                   1814:        .'<th>'.&mt('Part').'</th>'
                   1815:        .'<th>'.&mt('Points').'</th>'
                   1816:        .'<th>&nbsp;</th>'
                   1817:        .'<th>'.&mt('Assign Grade').'</th>'
                   1818:        .'<th>'.&mt('Weight').'</th>'
                   1819:        .'<th>'.&mt('Grade Status').'</th>'
                   1820:        .&Apache::loncommon::end_data_table_header_row()
                   1821:     );
                   1822: }
                   1823: 
                   1824: sub gradeBox_end {
                   1825:     return (
                   1826:         &Apache::loncommon::end_data_table()
                   1827:     );
                   1828: }
1.71      ng       1829: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1830: sub gradeBox {
1.322     albertel 1831:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1832:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1833: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1834:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1835:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1836:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1837:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1838:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1839: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1840:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1841:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1842:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1843: 				       [$partid]);
                   1844:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1845:     if ($last_resets{$partid}) {
                   1846:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1847:     }
1.695     bisitz   1848:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1849:     my $ctr = 0;
1.348     bowersj2 1850:     my $thisweight = 0;
1.349     albertel 1851:     my $increment = &get_increment();
1.485     albertel 1852: 
                   1853:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1854:     while ($thisweight<=$wgt) {
1.532     bisitz   1855: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1856:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1857: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1858: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1859: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1860:         $thisweight += $increment;
1.71      ng       1861: 	$ctr++;
                   1862:     }
1.485     albertel 1863:     $radio.='</tr></table>';
                   1864: 
                   1865:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1866: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1867: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1868: 	$wgt.')" /></td>'."\n";
1.485     albertel 1869:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1870: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1871: 	' </td>'."\n";
                   1872:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1873: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1874:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1875: 	$line.='<option></option>'.
                   1876: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1877:     } else {
1.485     albertel 1878: 	$line.='<option selected="selected"></option>'.
                   1879: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1880:     }
1.485     albertel 1881:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1882: 
                   1883: 
                   1884:     $result .= 
1.695     bisitz   1885: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1886:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1887:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1888:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1889: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1890: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1891: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1892:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1893:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1894:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1895:         $aggtries.'" />'."\n";
1.582     raeburn  1896:     my $res_error;
                   1897:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1898:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1899:     if ($res_error) {
                   1900:         return &navmap_errormsg();
                   1901:     }
1.318     banghart 1902:     return $result;
                   1903: }
1.322     albertel 1904: 
                   1905: sub handback_box {
1.623     www      1906:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1907:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1908:     my (@respids);
1.652     raeburn  1909:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1910:     foreach my $part_response_id (@part_response_id) {
                   1911:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1912:         if ($part eq $partid) {
1.375     albertel 1913:             push(@respids,$resp);
1.323     banghart 1914:         }
                   1915:     }
1.318     banghart 1916:     my $result;
1.323     banghart 1917:     foreach my $respid (@respids) {
1.322     albertel 1918: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1919: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1920: 	next if (!@$files);
1.654     raeburn  1921: 	my $file_counter = 0;
1.313     banghart 1922: 	foreach my $file (@$files) {
1.368     banghart 1923: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1924:                 $file_counter++;
1.368     banghart 1925:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1926:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1927:     	        $file_disp = "$name.$ext";
                   1928:     	        $file = $file_path.$file_disp;
                   1929:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1930:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1931:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1932:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1933: 	    }
1.322     albertel 1934: 	}
1.654     raeburn  1935:         if ($file_counter) {
                   1936:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1937:                        '<span class="LC_info">'.
                   1938:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1939:         }
1.313     banghart 1940:     }
1.318     banghart 1941:     return $result;    
1.71      ng       1942: }
1.44      ng       1943: 
1.58      albertel 1944: sub show_problem {
1.382     albertel 1945:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1946:     my $rendered;
1.382     albertel 1947:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1948:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1949:     if ($mode eq 'both' or $mode eq 'text') {
                   1950: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1951: 						       $env{'request.course.id'},
                   1952: 						       undef,\%form);
1.144     albertel 1953:     }
1.58      albertel 1954:     if ($removeform) {
                   1955: 	$rendered=~s|<form(.*?)>||g;
                   1956: 	$rendered=~s|</form>||g;
1.374     albertel 1957: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1958:     }
1.144     albertel 1959:     my $companswer;
                   1960:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1961: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1962: 	$companswer=
                   1963: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1964: 						    $env{'request.course.id'},
                   1965: 						    %form);
1.144     albertel 1966:     }
1.58      albertel 1967:     if ($removeform) {
                   1968: 	$companswer=~s|<form(.*?)>||g;
                   1969: 	$companswer=~s|</form>||g;
1.144     albertel 1970: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1971:     }
1.671     raeburn  1972:     my $renderheading = &mt('View of the problem');
                   1973:     my $answerheading = &mt('Correct answer');
                   1974:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1975:         my $stu_fullname = $env{'form.fullname'};
                   1976:         if ($stu_fullname eq '') {
                   1977:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1978:         }
                   1979:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1980:         if ($forwhom ne '') {
                   1981:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1982:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1983:         }
                   1984:     }
1.468     albertel 1985:     $rendered=
1.588     bisitz   1986:         '<div class="LC_Box">'
1.671     raeburn  1987:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1988:        .$rendered
                   1989:        .'</div>';
1.468     albertel 1990:     $companswer=
1.588     bisitz   1991:         '<div class="LC_Box">'
1.671     raeburn  1992:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1993:        .$companswer
                   1994:        .'</div>';
1.468     albertel 1995:     my $result;
1.144     albertel 1996:     if ($mode eq 'both') {
1.588     bisitz   1997:         $result=$rendered.$companswer;
1.144     albertel 1998:     } elsif ($mode eq 'text') {
1.588     bisitz   1999:         $result=$rendered;
1.144     albertel 2000:     } elsif ($mode eq 'answer') {
1.588     bisitz   2001:         $result=$companswer;
1.144     albertel 2002:     }
1.71      ng       2003:     return $result;
1.58      albertel 2004: }
1.397     albertel 2005: 
1.396     banghart 2006: sub files_exist {
                   2007:     my ($r, $symb) = @_;
                   2008:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2009:     foreach my $student (@students) {
                   2010:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2011:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2012: 					      $udom,$uname);
1.396     banghart 2013:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2014:         foreach my $submission (@$string) {
                   2015:             my ($partid,$respid) =
                   2016: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2017:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2018: 					   \%record);
                   2019:             return 1 if (@$files);
1.396     banghart 2020:         }
                   2021:     }
1.397     albertel 2022:     return 0;
1.396     banghart 2023: }
1.397     albertel 2024: 
1.394     banghart 2025: sub download_all_link {
                   2026:     my ($r,$symb) = @_;
1.621     www      2027:     unless (&files_exist($r, $symb)) {
1.766     raeburn  2028:         $r->print(&mt('There are currently no submitted documents.'));
                   2029:         return;
1.621     www      2030:     }
1.395     albertel 2031:     my $all_students = 
                   2032: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2033: 
                   2034:     my $parts =
                   2035: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2036: 
1.394     banghart 2037:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2038:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2039:                              'cgi.'.$identifier.'.symb' => $symb,
                   2040:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2041:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2042: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2043:     return;
                   2044: }
                   2045: 
                   2046: sub submit_download_link {
                   2047:     my ($request,$symb) = @_;
                   2048:     if (!$symb) { return ''; }
                   2049: #FIXME: Figure out which type of problem this is and provide appropriate download
1.750     raeburn  2050:     my $res_error;
                   2051:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                   2052:     if (ref($res_error)) {
                   2053:         if ($$res_error) {
                   2054:             $request->print(&mt('An error occurred retrieving response types'));
                   2055:             return;
                   2056:         }
                   2057:     }
                   2058:     my ($numupload,$numessay) = (0,0);
                   2059:     if (ref($responseType) eq 'HASH') {
                   2060:         foreach my $part (sort(keys(%$responseType))) {
                   2061:             foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
                   2062:                 my $responsetype = $responseType->{$part}->{$id};
                   2063:                 if ($responsetype eq 'essay') {
                   2064:                     my $uploadedfiletypes =
                   2065:                         &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
                   2066:                     if ($uploadedfiletypes) {
                   2067:                         $numupload++;
                   2068:                     } else {
                   2069:                         $numessay++;
                   2070:                     }
                   2071:                 }
                   2072:             }
                   2073:         }
                   2074:     }
                   2075:     if (($numupload) || ($numessay)) {
                   2076:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2077:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2078:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2079:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2080:         if (ref($fullname) eq 'HASH') {
                   2081:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2082:             if (@students) {
                   2083:                 @{$env{'form.stuinfo'}} = @students;
                   2084:                 if ($numupload) {
                   2085:                     &download_all_link($request,$symb);
                   2086:                 }
                   2087: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
                   2088: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2089:             } else {
                   2090:                 $request->print(&mt('No students match the criteria you selected'));
                   2091:             }
                   2092:         } else {
                   2093:             $request->print(&mt('Could not retrieve student information'));
                   2094:         }
                   2095:     } else {
                   2096:         $request->print(&mt('No essayresponse items found'));
                   2097:     }
                   2098:     return;
1.394     banghart 2099: }
1.395     albertel 2100: 
1.432     banghart 2101: sub build_section_inputs {
                   2102:     my $section_inputs;
                   2103:     if ($env{'form.section'} eq '') {
                   2104:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2105:     } else {
                   2106:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2107:         foreach my $section (@sections) {
1.432     banghart 2108:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2109:         }
                   2110:     }
                   2111:     return $section_inputs;
                   2112: }
                   2113: 
1.44      ng       2114: # --------------------------- show submissions of a student, option to grade 
                   2115: sub submission {
1.608     www      2116:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 2117:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2118:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2119:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2120:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2121: 
1.605     www      2122:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 2123:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.746     raeburn  2124:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  2125:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2126: 
                   2127:     if (!&canview($usec)) {
1.712     bisitz   2128:         $request->print(
                   2129:             '<span class="LC_warning">'.
1.713     bisitz   2130:             &mt('Unable to view requested student.').
1.712     bisitz   2131:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2132:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2133:             '</span>');
1.104     albertel 2134: 	return;
                   2135:     }
                   2136: 
1.257     albertel 2137:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2138:     unless ($is_tool) { 
                   2139:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2140:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2141:     }
1.257     albertel 2142:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2143:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2144: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2145: 	'/check.gif" height="16" border="0" />';
1.41      ng       2146: 
                   2147:     # header info
                   2148:     if ($counter == 0) {
                   2149: 	&sub_page_js($request);
1.621     www      2150: 	&sub_page_kw_js($request);
1.118     ng       2151: 
1.44      ng       2152: 	# option to display problem, only once else it cause problems 
                   2153:         # with the form later since the problem has a form.
1.257     albertel 2154: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2155: 	    my $mode;
1.257     albertel 2156: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2157: 		$mode='both';
1.257     albertel 2158: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2159: 		$mode='text';
1.257     albertel 2160: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2161: 		$mode='answer';
                   2162: 	    }
1.329     albertel 2163: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2164: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2165: 	}
1.441     www      2166: 
1.704     raeburn  2167: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2168:         # if this subroutine has been called once.
1.41      ng       2169: 	my %keyhash = ();
1.624     www      2170: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2171:         if (1) {
1.41      ng       2172: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2173: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2174: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2175: 
1.257     albertel 2176: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2177: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2178: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2179: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2180: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2181: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2182: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2183: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2184: 	}
1.257     albertel 2185: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2186: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2187: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2188: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2189: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2190: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2191: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2192: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2193: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2194: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2195: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2196: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2197: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2198: 			&build_section_inputs().
1.326     albertel 2199: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2200: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2201: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2202: #	if ($env{'form.handgrade'} eq 'yes') {
                   2203:         if (1) {
1.257     albertel 2204: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2205: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2206: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2207: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2208: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2209: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2210: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2211: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2212: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2213: 	    }
1.123     ng       2214: 	}
1.41      ng       2215: 	
                   2216: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2217: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2218: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2219: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2220: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2221: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2222: 		'" />'."\n".
                   2223: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2224: 	    $cts++;
                   2225: 	}
                   2226: 	$request->print($prnmsg);
1.32      ng       2227: 
1.624     www      2228: #	if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2229:         unless ($is_tool) {
1.652     raeburn  2230: 
                   2231:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2232:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2233:                           keyw => 'Keyword Options',
1.655     raeburn  2234:                           list => 'List',
1.652     raeburn  2235:                           past => 'Paste Selection to List',
1.661     www      2236:                           high => 'Highlight Attribute',
1.652     raeburn  2237:                      );    
1.88      www      2238: #
                   2239: # Print out the keyword options line
                   2240: #
1.718     bisitz   2241: 	    $request->print(
                   2242:                 '<div class="LC_columnSection">'
                   2243:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2244:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2245:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2246:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2247:  class="page">'.$lt{'past'}.'</a>',
                   2248:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2249:                     {legend => $lt{'keyw'}})
                   2250:                .'</fieldset></div>'
                   2251:             );
                   2252: 
1.88      www      2253: #
                   2254: # Load the other essays for similarity check
                   2255: #
1.753     raeburn  2256:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2257:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2258:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2259:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2260:                 if ($cdom ne '' && $cnum ne '') {
                   2261:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2262:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2263:                         my $apath = $1.'_'.$id;
                   2264:                         $apath=~s/\W/\_/gs;
                   2265:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2266:                     }
                   2267:                 }
                   2268:             } else {
                   2269: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2270: 	        $apath=&escape($apath);
                   2271: 	        $apath=~s/\W/\_/gs;
                   2272:                 &init_old_essays($symb,$apath,$adom,$aname);
                   2273:             }
1.41      ng       2274:         }
                   2275:     }
1.44      ng       2276: 
1.441     www      2277: # This is where output for one specific student would start
1.592     bisitz   2278:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2279:     $request->print(
                   2280:         "\n\n"
                   2281:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2282:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2283:        ."\n"
                   2284:     );
1.441     www      2285: 
1.592     bisitz   2286:     # Show additional functions if allowed
                   2287:     if ($perm{'vgr'}) {
                   2288:         $request->print(
                   2289:             &Apache::loncommon::track_student_link(
1.708     bisitz   2290:                 'View recent activity',
1.592     bisitz   2291:                 $uname,$udom,'check')
                   2292:            .' '
                   2293:         );
                   2294:     }
                   2295:     if ($perm{'opa'}) {
                   2296:         $request->print(
                   2297:             &Apache::loncommon::pprmlink(
                   2298:                 &mt('Set/Change parameters'),
                   2299:                 $uname,$udom,$symb,'check'));
                   2300:     }
                   2301: 
                   2302:     # Show Problem
1.257     albertel 2303:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2304: 	my $mode;
1.257     albertel 2305: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2306: 	    $mode='both';
1.257     albertel 2307: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2308: 	    $mode='text';
1.257     albertel 2309: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2310: 	    $mode='answer';
                   2311: 	}
1.329     albertel 2312: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2313: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2314:     }
1.144     albertel 2315: 
1.257     albertel 2316:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2317:     my $res_error;
                   2318:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2319:     if ($res_error) {
                   2320:         $request->print(&navmap_errormsg());
                   2321:         return;
                   2322:     }
1.41      ng       2323: 
1.44      ng       2324:     # Display student info
1.41      ng       2325:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2326: 
1.745     raeburn  2327:     my $boxtitle = &mt('Submissions');
                   2328:     if ($is_tool) {
                   2329:         $boxtitle = &mt('Transactions')
                   2330:     }
1.590     bisitz   2331:     my $result='<div class="LC_Box">'
1.745     raeburn  2332:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2333:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2334:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2335: #    if ($env{'form.handgrade'} eq 'no') {
1.745     raeburn  2336:     unless ($is_tool) {
1.588     bisitz   2337:         $result.='<p class="LC_info">'
                   2338:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2339:                 ."</p>\n";
1.469     albertel 2340:     }
                   2341: 
1.118     ng       2342:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2343:     my $fullname;
                   2344:     my $col_fullnames = [];
1.624     www      2345: #    if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2346:     unless ($is_tool) {
1.464     albertel 2347: 	(my $sub_result,$fullname,$col_fullnames)=
                   2348: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2349: 				 $counter);
                   2350: 	$result.=$sub_result;
1.41      ng       2351:     }
1.44      ng       2352:     $request->print($result."\n");
1.702     kruse    2353:     
1.44      ng       2354:     # print student answer/submission
1.588     bisitz   2355:     # Options are (1) Handgraded submission only
1.44      ng       2356:     #             (2) Last submission, includes submission that is not handgraded 
                   2357:     #                  (for multi-response type part)
                   2358:     #             (3) Last submission plus the parts info
                   2359:     #             (4) The whole record for this student
1.702     kruse    2360:     
1.745     raeburn  2361:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.468     albertel 2362: 	
1.702     kruse    2363:     my $lastsubonly;
1.468     albertel 2364: 
1.702     kruse    2365:     if ($$timestamp eq '') {
                   2366:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2367:     } elsif ($is_tool) {
                   2368:         $lastsubonly =
                   2369:             '<div class="LC_grade_submissions_body">'
                   2370:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2371:     } else {
                   2372:         $lastsubonly =
                   2373:             '<div class="LC_grade_submissions_body">'
                   2374:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2375: 
                   2376: 	my %seenparts;
                   2377: 	my @part_response_id = &flatten_responseType($responseType);
                   2378: 	foreach my $part (@part_response_id) {
                   2379: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2380: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2381: 
1.702     kruse    2382: 	    my ($partid,$respid) = @{ $part };
                   2383: 	    my $display_part=&get_display_part($partid,$symb);
                   2384: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2385: 		if (exists($seenparts{$partid})) { next; }
                   2386: 		$seenparts{$partid}=1;
                   2387:                 $request->print(
                   2388:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2389:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2390:                                '<a href="javascript:viewSubmitter(\''.
                   2391:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2392:                                '\');" target="_self">'.
                   2393:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2394:                     '<br />');
                   2395: 		next;
                   2396: 		}
                   2397: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2398: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2399:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2400:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2401:                     ' <span class="LC_internal_info">'.
                   2402:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2403:                     '</span>&nbsp; &nbsp;'.
                   2404: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2405: 		next;
                   2406: 	    }
                   2407: 	    foreach my $submission (@$string) {
                   2408: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2409: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2410: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2411: 		# Similarity check
                   2412:                 my $similar='';
                   2413:                 my ($type,$trial,$rndseed);
                   2414:                 if ($hide eq 'rand') {
                   2415:                     $type = 'randomizetry';
                   2416:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2417:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2418:                 }
                   2419: 	        if ($env{'form.checkPlag'}) {
                   2420:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2421: 		        &most_similar($uname,$udom,$symb,$subval);
                   2422: 		    if ($osim) {
                   2423: 			$osim=int($osim*100.0);
                   2424:                         if ($hide eq 'anon') {
                   2425:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2426:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2427:                         } else {
1.753     raeburn  2428: 			    $similar='<hr />';
                   2429:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2430:                                 $similar .= '<h3><span class="LC_warning">'.
                   2431:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2432:                                                 $osim,
                   2433:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2434:                                             '</span></h3>';
                   2435:                             } else {
                   2436:                                 my %old_course_desc;
                   2437:                                 if ($ocrsid ne '') {
                   2438:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2439:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
                   2440:                                     } else {
                   2441:                                         my $args;
                   2442:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2443:                                             $args = {'one_time' => 1};
                   2444:                                         }
                   2445:                                         %old_course_desc =
                   2446:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
                   2447:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
                   2448:                                     }
                   2449:                                     $similar .=
                   2450:                                         '<h3><span class="LC_warning">'.
                   2451:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2452:                                             $osim,
                   2453:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2454:                                             $old_course_desc{'description'},
                   2455:                                             $old_course_desc{'num'},
                   2456:                                             $old_course_desc{'domain'}).
                   2457:                                         '</span></h3>';
                   2458:                                 } else {
                   2459:                                     $similar .=
                   2460:                                         '<h3><span class="LC_warning">'.
                   2461:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2462:                                             $osim,
                   2463:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2464:                                         '</span></h3>';
                   2465:                                 }
                   2466:                             }
                   2467:                             $similar .= '<blockquote><i>'.
                   2468:                                         &keywords_highlight($oessay).
                   2469:                                         '</i></blockquote><hr />';
1.702     kruse    2470:                         }
                   2471: 	            }
                   2472: 		}
                   2473: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2474:                                      undef,$type,$trial,$rndseed);
                   2475:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2476: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2477: 		    my $display_part=&get_display_part($partid,$symb);
                   2478:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2479:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2480:                         ' <span class="LC_internal_info">'.
                   2481:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2482:                         '</span>&nbsp; &nbsp;';
                   2483: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2484:                         
                   2485: 		    if (@$files) {
                   2486:                         if ($hide eq 'anon') {
                   2487:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2488:                         } else {
                   2489:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2490:                                         .'<br /><span class="LC_warning">';
                   2491:                             if(@$files == 1) {
                   2492:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2493:                             } else {
1.702     kruse    2494:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2495:                             }
                   2496:                             $lastsubonly .= '</span>';                         
                   2497:                             foreach my $file (@$files) {
                   2498:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2499:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2500:                             }
                   2501:                         }
1.702     kruse    2502: 			$lastsubonly.='<br />';
                   2503:                     }
                   2504:                     if ($hide eq 'anon') {
                   2505:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2506:                     } else {
1.724     raeburn  2507:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2508:                         if ($draft) {
                   2509:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2510:                         }
                   2511:                         $subval =
1.702     kruse    2512: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2513: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2514:                         if ($responsetype eq 'essay') {
                   2515:                             $subval =~ s{\n}{<br />}g;
                   2516:                         }
                   2517:                         $lastsubonly.=$subval."\n";
1.702     kruse    2518:                     }
                   2519: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2520: 		    $lastsubonly.='</div>';
1.41      ng       2521: 		}
1.702     kruse    2522:             }
1.151     albertel 2523: 	}
1.702     kruse    2524: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2525:     }
                   2526:     $request->print($lastsubonly);
                   2527:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2528:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2529: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2530:   
1.702     kruse    2531:     } 
                   2532:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2533:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2534:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2535: 								 $env{'request.course.id'},
1.44      ng       2536: 								 $last,'.submission',
1.726     raeburn  2537: 								 'Apache::grades::keywords_highlight',
                   2538:                                                                  $usec,$identifier));
1.41      ng       2539:     }
1.121     ng       2540:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2541: 	.$udom.'" />'."\n");
1.44      ng       2542:     # return if view submission with no grading option
1.618     www      2543:     if (!&canmodify($usec)) {
1.633     www      2544: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2545: 	return;
1.180     albertel 2546:     } else {
1.468     albertel 2547: 	$request->print('</div>'."\n");
1.41      ng       2548:     }
1.33      ng       2549: 
1.121     ng       2550:     # essay grading message center
1.624     www      2551: #    if ($env{'form.handgrade'} eq 'yes') {
                   2552:     if (1) {
1.468     albertel 2553: 	my $result='<div class="LC_grade_message_center">';
                   2554:     
                   2555: 	$result.='<div class="LC_grade_message_center_header">'.
                   2556: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2557: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2558: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2559: 	if (scalar(@$col_fullnames) > 0) {
                   2560: 	    my $lastone = pop(@$col_fullnames);
                   2561: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2562: 	}
                   2563: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2564: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2565: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2566: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2567: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2568: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2569: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2570: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2571: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2572: 	    '<br />&nbsp;('.
1.468     albertel 2573: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2574: 	$result.='</div></div>';
1.121     ng       2575: 	$request->print($result);
1.118     ng       2576:     }
1.41      ng       2577: 
                   2578:     my %seen = ();
                   2579:     my @partlist;
1.129     ng       2580:     my @gradePartRespid;
1.745     raeburn  2581:     my @part_response_id;
                   2582:     if ($is_tool) {
                   2583:         @part_response_id = ([0,'']);
                   2584:     } else {
                   2585:         @part_response_id = &flatten_responseType($responseType);
                   2586:     }
1.585     bisitz   2587:     $request->print(
1.588     bisitz   2588:         '<div class="LC_Box">'
                   2589:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2590:     );
1.592     bisitz   2591:     $request->print(&gradeBox_start());
1.375     albertel 2592:     foreach my $part_response_id (@part_response_id) {
                   2593:     	my ($partid,$respid) = @{ $part_response_id };
                   2594: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2595: 	next if ($seen{$partid} > 0);
1.41      ng       2596: 	$seen{$partid}++;
1.393     albertel 2597: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2598: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2599: 	push(@partlist,$partid);
                   2600: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2601: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2602:     }
1.585     bisitz   2603:     $request->print(&gradeBox_end()); # </div>
                   2604:     $request->print('</div>');
1.468     albertel 2605: 
                   2606:     $request->print('<div class="LC_grade_info_links">');
                   2607:     $request->print('</div>');
                   2608: 
1.45      ng       2609:     $result='<input type="hidden" name="partlist'.$counter.
                   2610: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2611:     $result.='<input type="hidden" name="gradePartRespid'.
                   2612: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2613:     my $ctr = 0;
                   2614:     while ($ctr < scalar(@partlist)) {
                   2615: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2616: 	    $partlist[$ctr].'" />'."\n";
                   2617: 	$ctr++;
                   2618:     }
1.468     albertel 2619:     $request->print($result.''."\n");
1.41      ng       2620: 
1.441     www      2621: # Done with printing info for one student
                   2622: 
1.468     albertel 2623:     $request->print('</div>');#LC_grade_show_user
1.441     www      2624: 
                   2625: 
1.41      ng       2626:     # print end of form
                   2627:     if ($counter == $total) {
1.592     bisitz   2628:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2629: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2630: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2631: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2632: 	my $ntstu ='<select name="NTSTU">'.
                   2633: 	    '<option>1</option><option>2</option>'.
                   2634: 	    '<option>3</option><option>5</option>'.
                   2635: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2636: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2637: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2638:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2639: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2640: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2641: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2642: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2643:         $endform.='<span class="LC_warning">'.
                   2644:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2645:                   '</span>'."\n" ;
1.349     albertel 2646:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2647:             "' name='increment' />";
1.485     albertel 2648: 	$endform.='</td></tr></table></form>';
1.41      ng       2649: 	$request->print($endform);
                   2650:     }
                   2651:     return '';
1.38      ng       2652: }
                   2653: 
1.464     albertel 2654: sub check_collaborators {
                   2655:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2656:     my ($result,@col_fullnames);
                   2657:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2658:     foreach my $part (keys(%$handgrade)) {
                   2659: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2660: 					'.maxcollaborators',
                   2661: 					$symb,$udom,$uname);
                   2662: 	next if ($ncol <= 0);
                   2663: 	$part =~ s/\_/\./g;
                   2664: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2665: 	my (@good_collaborators, @bad_collaborators);
                   2666: 	foreach my $possible_collaborator
1.630     www      2667: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2668: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2669: 	    next if ($possible_collaborator eq '');
1.631     www      2670: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2671: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2672: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2673: 	    # Doing this grep allows 'fuzzy' specification
                   2674: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2675: 			       keys(%$classlist));
                   2676: 	    if (! scalar(@matches)) {
                   2677: 		push(@bad_collaborators, $possible_collaborator);
                   2678: 	    } else {
                   2679: 		push(@good_collaborators, @matches);
                   2680: 	    }
                   2681: 	}
                   2682: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2683: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2684: 	    foreach my $name (@good_collaborators) {
                   2685: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2686: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2687: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2688: 	    }
1.630     www      2689: 	    $result.='</ol><br />'."\n";
1.466     albertel 2690: 	    my ($part)=split(/\./,$part);
1.464     albertel 2691: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2692: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2693: 		"\n";
                   2694: 	}
                   2695: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2696: 	    $result.='<div class="LC_warning">';
1.464     albertel 2697: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2698: 	    $result .= '</div>';
                   2699: 	}         
                   2700: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2701: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2702: 	    $result .= &mt('This student has submitted too many '.
                   2703: 		'collaborators.  Maximum is [_1].',$ncol);
                   2704: 	    $result .= '</div>';
                   2705: 	}
                   2706:     }
                   2707:     return ($result,$fullname,\@col_fullnames);
                   2708: }
                   2709: 
1.44      ng       2710: #--- Retrieve the last submission for all the parts
1.38      ng       2711: sub get_last_submission {
1.745     raeburn  2712:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2713:     my (@string,$timestamp,%lasthidden);
1.119     ng       2714:     if ($$returnhash{'version'}) {
1.46      ng       2715: 	my %lasthash=();
                   2716: 	my ($version);
1.119     ng       2717: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2718: 	    foreach my $key (sort(split(/\:/,
                   2719: 					$$returnhash{$version.':keys'}))) {
                   2720: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2721: 		$timestamp = 
1.545     raeburn  2722: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2723: 	    }
                   2724: 	}
1.640     raeburn  2725:         my (%typeparts,%randombytry);
1.596     raeburn  2726:         my $showsurv = 
                   2727:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2728:         foreach my $key (sort(keys(%lasthash))) {
                   2729:             if ($key =~ /\.type$/) {
                   2730:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2731:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2732:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2733:                     my ($ign,@parts) = split(/\./,$key);
                   2734:                     pop(@parts);
1.641     raeburn  2735:                     my $id = join('.',@parts);
1.640     raeburn  2736:                     if ($lasthash{$key} eq 'randomizetry') {
                   2737:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2738:                     } else {
                   2739:                         unless ($showsurv) {
                   2740:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2741:                         }
1.596     raeburn  2742:                     }
                   2743:                     delete($lasthash{$key});
                   2744:                 }
                   2745:             }
                   2746:         }
                   2747:         my @hidden = keys(%typeparts);
1.640     raeburn  2748:         my @randomize = keys(%randombytry);
1.397     albertel 2749: 	foreach my $key (keys(%lasthash)) {
                   2750: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2751:             my $hide;
                   2752:             if (@hidden) {
                   2753:                 foreach my $id (@hidden) {
                   2754:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2755:                         $hide = 'anon';
1.596     raeburn  2756:                         last;
                   2757:                     }
                   2758:                 }
                   2759:             }
1.640     raeburn  2760:             unless ($hide) {
                   2761:                 if (@randomize) {
1.732     raeburn  2762:                     foreach my $id (@randomize) {
1.640     raeburn  2763:                         if ($key =~ /^\Q$id\E/) {
                   2764:                             $hide = 'rand';
                   2765:                             last;
                   2766:                         }
                   2767:                     }
                   2768:                 }
                   2769:             }
1.397     albertel 2770: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2771: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2772:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2773:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2774:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2775: 	}
                   2776:     }
1.397     albertel 2777:     if (!@string) {
1.745     raeburn  2778:         my $msg;
                   2779:         if ($is_tool) {
1.747     raeburn  2780:             $msg = &mt('No grade passed back.');
1.745     raeburn  2781:         } else {
                   2782:             $msg = &mt('Nothing submitted - no attempts.');
                   2783:         }
1.397     albertel 2784: 	$string[0] =
1.745     raeburn  2785: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2786:     }
                   2787:     return (\@string,\$timestamp);
1.38      ng       2788: }
1.35      ng       2789: 
1.44      ng       2790: #--- High light keywords, with style choosen by user.
1.38      ng       2791: sub keywords_highlight {
1.44      ng       2792:     my $string    = shift;
1.257     albertel 2793:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2794:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2795:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2796:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2797:     foreach my $keyword (@keylist) {
                   2798: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2799:     }
                   2800:     return $string;
1.38      ng       2801: }
1.36      ng       2802: 
1.671     raeburn  2803: # For Tasks provide a mechanism to display previous version for one specific student
                   2804: 
                   2805: sub show_previous_task_version {
                   2806:     my ($request,$symb) = @_;
                   2807:     if ($symb eq '') {
1.717     bisitz   2808:         $request->print(
                   2809:             '<span class="LC_error">'.
                   2810:             &mt('Unable to handle ambiguous references.').
                   2811:             '</span>');
1.671     raeburn  2812:         return '';
                   2813:     }
                   2814:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2815:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2816:     if (!&canview($usec)) {
1.712     bisitz   2817:         $request->print(
                   2818:             '<span class="LC_warning">'.
1.713     bisitz   2819:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2820:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2821:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2822:             '</span>');
1.671     raeburn  2823:         return;
                   2824:     }
                   2825:     my $mode = 'both';
                   2826:     my $isTask = ($symb =~/\.task$/);
                   2827:     if ($isTask) {
                   2828:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2829:             if ($env{'form.fullname'} eq '') {
                   2830:                 $env{'form.fullname'} =
                   2831:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2832:             }
                   2833:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2834:             $request->print("\n\n".
                   2835:                             '<div class="LC_grade_show_user">'.
                   2836:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2837:                             '</h2>'."\n");
                   2838:             &Apache::lonxml::clear_problem_counter();
                   2839:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2840:                             {'previousversion' => $env{'form.previousversion'} }));
                   2841:             $request->print("\n</div>");
                   2842:         }
                   2843:     }
                   2844:     return;
                   2845: }
                   2846: 
                   2847: sub choose_task_version_form {
                   2848:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2849:     my $isTask = ($symb =~/\.task$/);
                   2850:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2851:     if ($isTask) {
                   2852:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2853:                                               $udom,$uname);
                   2854:         if (($record{'resource.0.version'} eq '') ||
                   2855:             ($record{'resource.0.version'} < 2)) {
                   2856:             return ($record{'resource.0.version'},
                   2857:                     $record{'resource.0.version'},$result,$js);
                   2858:         } else {
                   2859:             $current = $record{'resource.0.version'};
                   2860:         }
                   2861:         if ($env{'form.previousversion'}) {
                   2862:             $displayed = $env{'form.previousversion'};
                   2863:             $rowtitle = &mt('Choose another version:')
                   2864:         } else {
                   2865:             $displayed = $current;
                   2866:             $rowtitle = &mt('Show earlier version:');
                   2867:         }
                   2868:         $result = '<div class="LC_left_float">';
                   2869:         my $list;
                   2870:         my $numversions = 0;
                   2871:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2872:             if ($i == $current) {
                   2873:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2874:                     next;
                   2875:                 } else {
                   2876:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2877:                     $numversions ++;
                   2878:                 }
                   2879:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2880:                 unless ($i == $env{'form.previousversion'}) {
                   2881:                     $numversions ++;
                   2882:                 }
                   2883:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2884:             }
                   2885:         }
                   2886:         if ($numversions) {
                   2887:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2888:             $result .=
                   2889:                 '<form name="getprev" method="post" action=""'.
                   2890:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2891:                 &Apache::loncommon::start_data_table().
                   2892:                 &Apache::loncommon::start_data_table_row().
                   2893:                 '<th align="left">'.$rowtitle.'</th>'.
                   2894:                 '<td><select name="version">'.
                   2895:                 '<option>'.&mt('Select').'</option>'.
                   2896:                 $list.
                   2897:                 '</select></td>'.
                   2898:                 &Apache::loncommon::end_data_table_row();
                   2899:             unless ($nomenu) {
                   2900:                 $result .= &Apache::loncommon::start_data_table_row().
                   2901:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2902:                 '<td><span class="LC_nobreak">'.
                   2903:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2904:                 &mt('Yes').'</label>'.
                   2905:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2906:                 '</span></td>'.
                   2907:                 &Apache::loncommon::end_data_table_row();
                   2908:             }
                   2909:             $result .=
                   2910:                 &Apache::loncommon::start_data_table_row().
                   2911:                 '<th align="left">&nbsp;</th>'.
                   2912:                 '<td>'.
                   2913:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2914:                 '</td>'.
                   2915:                 &Apache::loncommon::end_data_table_row().
                   2916:                 &Apache::loncommon::end_data_table().
                   2917:                 '</form>';
                   2918:             $js = &previous_display_javascript($nomenu,$current);
                   2919:         } elsif ($displayed && $nomenu) {
                   2920:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2921:         } else {
                   2922:             $result .= &mt('No previous versions to show for this student');
                   2923:         }
                   2924:         $result .= '</div>';
                   2925:     }
                   2926:     return ($current,$displayed,$result,$js);
                   2927: }
                   2928: 
                   2929: sub previous_display_javascript {
                   2930:     my ($nomenu,$current) = @_;
                   2931:     my $js = <<"JSONE";
                   2932: <script type="text/javascript">
                   2933: // <![CDATA[
                   2934: function previousVersion(uname,udom,symb) {
                   2935:     var current = '$current';
                   2936:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2937:     var prevstr = new RegExp("^\\\\d+\$");
                   2938:     if (!prevstr.test(version)) {
                   2939:         return false;
                   2940:     }
                   2941:     var url = '';
                   2942:     if (version == current) {
                   2943:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2944:     } else {
                   2945:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2946:     }
                   2947: JSONE
                   2948:     if ($nomenu) {
                   2949:         $js .= <<"JSTWO";
                   2950:     document.location.href = url;
                   2951: JSTWO
                   2952:     } else {
                   2953:         $js .= <<"JSTHREE";
                   2954:     var newwin = 0;
                   2955:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2956:         if (document.getprev.prevwin[i].checked == true) {
                   2957:             newwin = document.getprev.prevwin[i].value;
                   2958:         }
                   2959:     }
                   2960:     if (newwin == 1) {
                   2961:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2962:         url = url+'&inhibitmenu=yes';
                   2963:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2964:             previousWin = window.open(url,'',options,1);
                   2965:         } else {
                   2966:             previousWin.location.href = url;
                   2967:         }
                   2968:         previousWin.focus();
                   2969:         return false;
                   2970:     } else {
                   2971:         document.location.href = url;
                   2972:         return false;
                   2973:     }
                   2974: JSTHREE
                   2975:     }
                   2976:     $js .= <<"ENDJS";
                   2977:     return false;
                   2978: }
                   2979: // ]]>
                   2980: </script>
                   2981: ENDJS
                   2982: 
                   2983: }
                   2984: 
1.44      ng       2985: #--- Called from submission routine
1.38      ng       2986: sub processHandGrade {
1.608     www      2987:     my ($request,$symb) = @_;
1.324     albertel 2988:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2989:     my $button = $env{'form.gradeOpt'};
                   2990:     my $ngrade = $env{'form.NCT'};
                   2991:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2992:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2993:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2994: 
1.44      ng       2995:     if ($button eq 'Save & Next') {
                   2996: 	my $ctr = 0;
                   2997: 	while ($ctr < $ngrade) {
1.257     albertel 2998: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  2999: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3000:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3001: 	    if ($errorflag eq 'no_score') {
                   3002: 		$ctr++;
                   3003: 		next;
                   3004: 	    }
1.104     albertel 3005: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3006: 		$request->print(
                   3007:                     '<span class="LC_error">'
                   3008:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3009:                    .'</span>');
1.104     albertel 3010: 		$ctr++;
                   3011: 		next;
                   3012: 	    }
1.726     raeburn  3013:             if ($numhidden) {
                   3014:                 $request->print(
                   3015:                     '<span class="LC_info">'
                   3016:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3017:                    .'</span><br />');
                   3018:             }
1.257     albertel 3019: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3020: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3021: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3022:             my ($feedurl,$showsymb) =
                   3023: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3024: 	    my $messagetail;
1.62      albertel 3025: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3026: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3027: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3028: 		$subject.=' ['.$restitle.']';
1.44      ng       3029: 		my (@msgnum) = split(/,/,$includemsg);
                   3030: 		foreach (@msgnum) {
1.257     albertel 3031: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3032: 		}
1.80      ng       3033: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3034: 		if ($env{'form.withgrades'.$ctr}) {
                   3035: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3036: 		    $messagetail = " for <a href=\"".
1.605     www      3037: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3038: 		}
                   3039: 		$msgstatus = 
                   3040:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3041: 						     $message.$messagetail,
1.418     albertel 3042:                                                      undef,$feedurl,undef,
1.386     raeburn  3043:                                                      undef,undef,$showsymb,
                   3044:                                                      $restitle);
1.574     bisitz   3045: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3046: 				$msgstatus.'<br />');
1.44      ng       3047: 	    }
1.257     albertel 3048: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3049: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3050: 		foreach my $collabstr (@collabstrs) {
                   3051: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3052: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3053: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3054: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3055: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3056: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3057: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3058: 			    next;
1.418     albertel 3059: 			} elsif ($message ne '') {
                   3060: 			    my ($baseurl,$showsymb) = 
                   3061: 				&get_feedurl_and_symb($symb,$collaborator,
                   3062: 						      $udom);
                   3063: 			    if ($env{'form.withgrades'.$ctr}) {
                   3064: 				$messagetail = " for <a href=\"".
1.605     www      3065:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3066: 			    }
1.418     albertel 3067: 			    $msgstatus = 
                   3068: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3069: 			}
1.44      ng       3070: 		    }
                   3071: 		}
                   3072: 	    }
                   3073: 	    $ctr++;
                   3074: 	}
                   3075:     }
                   3076: 
1.624     www      3077: #    if ($env{'form.handgrade'} eq 'yes') {
                   3078:     if (1) {
1.119     ng       3079: 	# Keywords sorted in alphabatical order
1.257     albertel 3080: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       3081: 	my %keyhash = ();
1.257     albertel 3082: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   3083: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   3084: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3085: 	$env{'form.keywords'} = join(' ',@keywords);
                   3086: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3087: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3088: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3089: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3090: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       3091: 
                   3092: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3093: 	# New messages are saved in env for the next student.
1.119     ng       3094: 	# All messages are saved in nohist_handgrade.db
                   3095: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3096: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3097: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3098: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3099: 		$idx++;
                   3100: 	    }
                   3101: 	    $ctr++;
1.41      ng       3102: 	}
1.119     ng       3103: 	$ctr = 0;
                   3104: 	while ($ctr < $ngrade) {
1.257     albertel 3105: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3106: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3107: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3108: 		$idx++;
                   3109: 	    }
                   3110: 	    $ctr++;
1.41      ng       3111: 	}
1.257     albertel 3112: 	$env{'form.savemsgN'} = --$idx;
                   3113: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       3114: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3115: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3116:     }
1.44      ng       3117:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3118:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3119:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3120: 	my ($ctr,$total) = (0,0);
                   3121: 	while ($ctr < $ngrade) {
1.257     albertel 3122: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3123: 	    $ctr++;
                   3124: 	}
1.257     albertel 3125: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3126: 	$ctr = 0;
                   3127: 	while ($ctr < $total) {
1.257     albertel 3128: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3129: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3130: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3131: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3132: 	    $ctr++;
                   3133: 	}
                   3134: 	return '';
                   3135:     }
1.36      ng       3136: 
1.44      ng       3137:     # Get the next/previous one or group of students
1.257     albertel 3138:     my $firststu = $env{'form.unamedom0'};
                   3139:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3140:     my $ctr = 2;
1.41      ng       3141:     while ($laststu eq '') {
1.257     albertel 3142: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3143: 	$ctr++;
                   3144: 	$laststu = $firststu if ($ctr > $ngrade);
                   3145:     }
1.44      ng       3146: 
1.41      ng       3147:     my (@parsedlist,@nextlist);
                   3148:     my ($nextflg) = 0;
1.524     raeburn  3149:     foreach my $item (sort 
1.294     albertel 3150: 	     {
                   3151: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3152: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3153: 		 }
                   3154: 		 return $a cmp $b;
                   3155: 	     } (keys(%$fullname))) {
1.605     www      3156: # FIXME: this is fishy, looks like the button label
1.41      ng       3157: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3158: 	    push(@parsedlist,$item);
1.41      ng       3159: 	}
1.524     raeburn  3160: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3161: 	if ($button eq 'Previous') {
1.524     raeburn  3162: 	    last if ($item eq $firststu);
                   3163: 	    push(@parsedlist,$item);
1.41      ng       3164: 	}
                   3165:     }
                   3166:     $ctr = 0;
1.605     www      3167: # FIXME: this is fishy, looks like the button label
1.41      ng       3168:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3169:     my $res_error;
                   3170:     my ($partlist) = &response_type($symb,\$res_error);
                   3171:     if ($res_error) {
                   3172:         $request->print(&navmap_errormsg());
                   3173:         return;
                   3174:     }
1.41      ng       3175:     foreach my $student (@parsedlist) {
1.257     albertel 3176: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3177: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3178: 	
                   3179: 	if ($submitonly eq 'queued') {
                   3180: 	    my %queue_status = 
                   3181: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3182: 							$udom,$uname);
                   3183: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3184: 	}
                   3185: 
1.156     albertel 3186: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3187: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3188: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3189: 	    my $submitted = 0;
1.248     albertel 3190: 	    my $ungraded = 0;
                   3191: 	    my $incorrect = 0;
1.524     raeburn  3192: 	    foreach my $item (keys(%status)) {
                   3193: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3194: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3195: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3196: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3197: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3198: 		    $submitted = 0;
                   3199: 		}
1.41      ng       3200: 	    }
1.156     albertel 3201: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3202: 				     $submitonly eq 'incorrect' ||
                   3203: 				     $submitonly eq 'graded'));
1.248     albertel 3204: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3205: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3206: 	}
1.524     raeburn  3207: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3208: 	last if ($ctr == $ntstu);
1.41      ng       3209: 	$ctr++;
                   3210:     }
1.36      ng       3211: 
1.41      ng       3212:     $ctr = 0;
                   3213:     my $total = scalar(@nextlist)-1;
1.39      ng       3214: 
1.524     raeburn  3215:     foreach (sort(@nextlist)) {
1.41      ng       3216: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3217: 	$env{'form.student'}  = $uname;
                   3218: 	$env{'form.userdom'}  = $udom;
                   3219: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3220: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3221: 	$ctr++;
                   3222:     }
                   3223:     if ($total < 0) {
1.653     raeburn  3224: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3225: 	$request->print($the_end);
                   3226:     }
                   3227:     return '';
1.38      ng       3228: }
1.36      ng       3229: 
1.44      ng       3230: #---- Save the score and award for each student, if changed
1.38      ng       3231: sub saveHandGrade {
1.324     albertel 3232:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3233:     my @version_parts;
1.104     albertel 3234:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3235: 					   $env{'request.course.id'});
1.104     albertel 3236:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3237:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3238:     my @parts_graded;
1.77      ng       3239:     my %newrecord  = ();
1.726     raeburn  3240:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3241:     my %aggregate = ();
                   3242:     my $aggregateflag = 0;
1.726     raeburn  3243:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3244:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3245:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3246:         $totchg += $numchgs;
                   3247:     }
1.301     albertel 3248:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3249:     foreach my $new_part (@parts) {
1.337     banghart 3250: 	#collaborator ($submi may vary for different parts
1.259     banghart 3251: 	if ($submitter && $new_part ne $part) { next; }
                   3252: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3253: 	if ($dropMenu eq 'excused') {
1.259     banghart 3254: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3255: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3256: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3257: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3258: 		}
1.364     banghart 3259: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3260: 	    }
1.125     ng       3261: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3262: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3263: 	    foreach my $key (keys(%record)) {
1.259     banghart 3264: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3265: 	    }
1.259     banghart 3266: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3267: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3268:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3269: 
                   3270:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3271: 					       [$new_part]);
                   3272:             my $aggtries =$totaltries;
1.269     raeburn  3273:             if ($last_resets{$new_part}) {
1.270     albertel 3274:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3275: 					   $new_part);
1.269     raeburn  3276:             }
1.270     albertel 3277: 
                   3278:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3279:             if ($aggtries > 0) {
1.327     albertel 3280:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3281:                 $aggregateflag = 1;
                   3282:             }
1.125     ng       3283: 	} elsif ($dropMenu eq '') {
1.259     banghart 3284: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3285: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3286: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3287: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3288: 		next;
                   3289: 	    }
1.259     banghart 3290: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3291: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3292: 	    my $partial= $pts/$wgt;
1.259     banghart 3293: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3294: 		#do not update score for part if not changed.
1.346     banghart 3295:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3296: 		next;
1.251     banghart 3297: 	    } else {
1.524     raeburn  3298: 	        push(@parts_graded,$new_part);
1.153     albertel 3299: 	    }
1.259     banghart 3300: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3301: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3302: 	    }
1.259     banghart 3303: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3304: 	    if ($partial == 0) {
1.153     albertel 3305: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3306: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3307: 		}
1.41      ng       3308: 	    } else {
1.153     albertel 3309: 		if ($record{$reckey} ne 'correct_by_override') {
                   3310: 		    $newrecord{$reckey} = 'correct_by_override';
                   3311: 		}
                   3312: 	    }	    
                   3313: 	    if ($submitter && 
1.259     banghart 3314: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3315: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3316: 	    }
1.259     banghart 3317: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3318: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3319: 	}
1.259     banghart 3320: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3321: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3322: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3323: 	        $dropMenu eq 'reset status')
                   3324: 	   {
1.524     raeburn  3325: 	    push(@version_parts,$new_part);
1.259     banghart 3326: 	}
1.41      ng       3327:     }
1.301     albertel 3328:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3329:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3330: 
1.344     albertel 3331:     if (%newrecord) {
                   3332:         if (@version_parts) {
1.364     banghart 3333:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3334:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3335: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3336: 	    foreach my $new_part (@version_parts) {
                   3337: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3338: 				$new_part,\%newrecord);
                   3339: 	    }
1.259     banghart 3340:         }
1.44      ng       3341: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3342: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3343: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3344: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3345:     }
1.269     raeburn  3346:     if ($aggregateflag) {
                   3347:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3348: 			      $cdom,$cnum);
1.269     raeburn  3349:     }
1.726     raeburn  3350:     return ('',$pts,$wgt,$totchg);
                   3351: }
                   3352: 
                   3353: sub makehidden {
1.728     raeburn  3354:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3355:     return unless (ref($record) eq 'HASH');
                   3356:     my %modified;
                   3357:     my $numchanged = 0;
                   3358:     if (exists($record->{$version.':keys'})) {
                   3359:         my $partsregexp = $parts;
                   3360:         $partsregexp =~ s/,/|/g;
                   3361:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3362:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3363:                  my $item = $1;
                   3364:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3365:                      $modified{$key} = $record->{$version.':'.$key};
                   3366:                  }
                   3367:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3368:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3369:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3370:                 $modified{$key} = $record->{$version.':'.$key};
                   3371:             }
                   3372:         }
                   3373:         if (keys(%modified)) {
                   3374:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3375:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3376:                 $numchanged ++;
                   3377:             }
                   3378:         }
                   3379:     }
                   3380:     return $numchanged;
1.36      ng       3381: }
1.322     albertel 3382: 
1.380     albertel 3383: sub check_and_remove_from_queue {
                   3384:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3385:     my @ungraded_parts;
                   3386:     foreach my $part (@{$parts}) {
                   3387: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3388: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3389: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3390: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3391: 		) {
                   3392: 	    push(@ungraded_parts, $part);
                   3393: 	}
                   3394:     }
                   3395:     if ( !@ungraded_parts ) {
                   3396: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3397: 					       $cnum,$domain,$stuname);
                   3398:     }
                   3399: }
                   3400: 
1.337     banghart 3401: sub handback_files {
                   3402:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3403:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3404:     my $res_error;
                   3405:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3406:     if ($res_error) {
                   3407:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3408:         return;
                   3409:     }
1.654     raeburn  3410:     my @handedback;
                   3411:     my $file_msg;
1.375     albertel 3412:     my @part_response_id = &flatten_responseType($responseType);
                   3413:     foreach my $part_response_id (@part_response_id) {
                   3414:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3415: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3416:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3417:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3418:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3419:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3420:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3421:                     my ($directory,$answer_file) = 
1.654     raeburn  3422:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3423:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3424: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3425: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3426:                     my $getpropath = 1;
1.662     raeburn  3427:                     my ($dir_list,$listerror) = 
                   3428:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3429:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3430: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3431:                     # fix filename
1.355     banghart 3432:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3433:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3434:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3435:             	                                $save_file_name);
1.337     banghart 3436:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3437:                         $request->print('<br /><span class="LC_error">'.
                   3438:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3439:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3440:                                         '</span>');
1.356     banghart 3441:                     } else {
1.360     banghart 3442:                         # mark the file as read only
1.654     raeburn  3443:                         push(@handedback,$save_file_name);
1.367     albertel 3444: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3445: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3446: 			}
                   3447:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3448: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3449:                     }
1.686     bisitz   3450:                     $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 3451:                 }
                   3452:             }
                   3453:         }
1.654     raeburn  3454:     }
                   3455:     if (@handedback > 0) {
                   3456:         $request->print('<br />');
                   3457:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3458:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3459:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3460:         my ($subject,$message);
                   3461:         if (scalar(@handedback) == 1) {
                   3462:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3463:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3464:         } else {
                   3465:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3466:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3467:         }
                   3468:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3469:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3470:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3471:         my ($feedurl,$showsymb) =
                   3472:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3473:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3474:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3475:         my $msgstatus =
                   3476:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3477:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3478:                  $restitle);
                   3479:         if ($msgstatus) {
                   3480:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3481:         }
                   3482:     }
1.338     banghart 3483:     return;
1.337     banghart 3484: }
                   3485: 
1.418     albertel 3486: sub get_feedurl_and_symb {
                   3487:     my ($symb,$uname,$udom) = @_;
                   3488:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3489:     $url = &Apache::lonnet::clutter($url);
                   3490:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3491: 					$symb,$udom,$uname);
                   3492:     if ($encrypturl =~ /^yes$/i) {
                   3493: 	&Apache::lonenc::encrypted(\$url,1);
                   3494: 	&Apache::lonenc::encrypted(\$symb,1);
                   3495:     }
                   3496:     return ($url,$symb);
                   3497: }
                   3498: 
1.313     banghart 3499: sub get_submitted_files {
                   3500:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3501:     my @files;
                   3502:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3503:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3504:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3505:     	    push(@files,$file_url.$file);
                   3506:         }
                   3507:     }
                   3508:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3509:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3510:     }
                   3511:     return (\@files);
                   3512: }
1.322     albertel 3513: 
1.269     raeburn  3514: # ----------- Provides number of tries since last reset.
                   3515: sub get_num_tries {
                   3516:     my ($record,$last_reset,$part) = @_;
                   3517:     my $timestamp = '';
                   3518:     my $num_tries = 0;
                   3519:     if ($$record{'version'}) {
                   3520:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3521:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3522:                 $timestamp = $$record{$version.':timestamp'};
                   3523:                 if ($timestamp > $last_reset) {
                   3524:                     $num_tries ++;
                   3525:                 } else {
                   3526:                     last;
                   3527:                 }
                   3528:             }
                   3529:         }
                   3530:     }
                   3531:     return $num_tries;
                   3532: }
                   3533: 
                   3534: # ----------- Determine decrements required in aggregate totals 
                   3535: sub decrement_aggs {
                   3536:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3537:     my %decrement = (
                   3538:                         attempts => 0,
                   3539:                         users => 0,
                   3540:                         correct => 0
                   3541:                     );
                   3542:     $decrement{'attempts'} = $aggtries;
                   3543:     if ($solvedstatus =~ /^correct/) {
                   3544:         $decrement{'correct'} = 1;
                   3545:     }
                   3546:     if ($aggtries == $totaltries) {
                   3547:         $decrement{'users'} = 1;
                   3548:     }
1.524     raeburn  3549:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3550:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3551:     }
                   3552:     return;
                   3553: }
                   3554: 
                   3555: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3556: sub get_last_resets {
1.270     albertel 3557:     my ($symb,$courseid,$partids) =@_;
                   3558:     my %last_resets;
1.269     raeburn  3559:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3560:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3561:     my @keys;
                   3562:     foreach my $part (@{$partids}) {
                   3563: 	push(@keys,"$symb\0$part\0resettime");
                   3564:     }
                   3565:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3566: 				     $cdom,$cname);
                   3567:     foreach my $part (@{$partids}) {
                   3568: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3569:     }
1.270     albertel 3570:     return %last_resets;
1.269     raeburn  3571: }
                   3572: 
1.251     banghart 3573: # ----------- Handles creating versions for portfolio files as answers
                   3574: sub version_portfiles {
1.343     banghart 3575:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3576:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3577:     my @returned_keys;
1.255     banghart 3578:     my $parts = join('|', @$parts_graded);
1.277     albertel 3579:     foreach my $key (keys(%$record)) {
1.259     banghart 3580:         my $new_portfiles;
1.263     banghart 3581:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3582:             my @versioned_portfiles;
1.367     albertel 3583:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3584:             if (@portfiles) {
                   3585:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3586:                                                       \@versioned_portfiles);
1.252     banghart 3587:             }
1.343     banghart 3588:             $$record{$key} = join(',',@versioned_portfiles);
                   3589:             push(@returned_keys,$key);
1.251     banghart 3590:         }
                   3591:     } 
1.343     banghart 3592:     return (@returned_keys);   
1.305     banghart 3593: }
                   3594: 
1.44      ng       3595: #--------------------------------------------------------------------------------------
                   3596: #
                   3597: #-------------------------- Next few routines handles grading by section or whole class
                   3598: #
                   3599: #--- Javascript to handle grading by section or whole class
1.42      ng       3600: sub viewgrades_js {
                   3601:     my ($request) = shift;
                   3602: 
1.539     riegler  3603:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3604:     &js_escape(\$alertmsg);
1.597     wenzelju 3605:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3606:    function writePoint(partid,weight,point) {
1.125     ng       3607: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3608: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3609: 	if (point == "textval") {
1.125     ng       3610: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3611: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3612: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3613: 		var resetbox = false;
                   3614: 		for (var i=0; i<radioButton.length; i++) {
                   3615: 		    if (radioButton[i].checked) {
                   3616: 			textbox.value = i;
                   3617: 			resetbox = true;
                   3618: 		    }
                   3619: 		}
                   3620: 		if (!resetbox) {
                   3621: 		    textbox.value = "";
                   3622: 		}
                   3623: 		return;
                   3624: 	    }
1.109     matthew  3625: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3626: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3627: 				   ") greater than the weight for the part. Accept?");
                   3628: 		if (resp == false) {
                   3629: 		    textbox.value = "";
                   3630: 		    return;
                   3631: 		}
                   3632: 	    }
1.42      ng       3633: 	    for (var i=0; i<radioButton.length; i++) {
                   3634: 		radioButton[i].checked=false;
1.109     matthew  3635: 		if (parseFloat(point) == i) {
1.42      ng       3636: 		    radioButton[i].checked=true;
                   3637: 		}
                   3638: 	    }
1.41      ng       3639: 
1.42      ng       3640: 	} else {
1.125     ng       3641: 	    textbox.value = parseFloat(point);
1.42      ng       3642: 	}
1.41      ng       3643: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3644: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3645: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3646: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3647: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3648: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3649: 	    if (saveval != "correct") {
                   3650: 		scorename.value = point;
1.43      ng       3651: 		if (selname[0].selected != true) {
                   3652: 		    selname[0].selected = true;
                   3653: 		}
1.42      ng       3654: 	    }
                   3655: 	}
1.125     ng       3656: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3657:     }
                   3658: 
                   3659:     function writeRadText(partid,weight) {
1.125     ng       3660: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3661: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3662:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3663: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3664: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3665: 	    for (var i=0; i<radioButton.length; i++) {
                   3666: 		radioButton[i].checked=false;
                   3667: 
                   3668: 	    }
                   3669: 	    textbox.value = "";
                   3670: 
                   3671: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3672: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3673: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3674: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3675: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3676: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3677: 		if ((saveval != "correct") || override) {
1.42      ng       3678: 		    scorename.value = "";
1.125     ng       3679: 		    if (selval[1].selected) {
                   3680: 			selname[1].selected = true;
                   3681: 		    } else {
                   3682: 			selname[2].selected = true;
                   3683: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3684: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3685: 		    }
1.42      ng       3686: 		}
                   3687: 	    }
1.43      ng       3688: 	} else {
                   3689: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3690: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3691: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3692: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3693: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3694: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3695: 		if ((saveval != "correct") || override) {
1.125     ng       3696: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3697: 		    selname[0].selected = true;
                   3698: 		}
                   3699: 	    }
                   3700: 	}	    
1.42      ng       3701:     }
                   3702: 
                   3703:     function changeSelect(partid,user) {
1.125     ng       3704: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3705: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3706: 	var point  = textbox.value;
1.125     ng       3707: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3708: 
1.109     matthew  3709: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3710: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3711: 	    textbox.value = "";
                   3712: 	    return;
                   3713: 	}
1.109     matthew  3714: 	if (parseFloat(point) > parseFloat(weight)) {
                   3715: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3716: 			       ") greater than the weight of the part. Accept?");
                   3717: 	    if (resp == false) {
                   3718: 		textbox.value = "";
                   3719: 		return;
                   3720: 	    }
                   3721: 	}
1.42      ng       3722: 	selval[0].selected = true;
                   3723:     }
                   3724: 
                   3725:     function changeOneScore(partid,user) {
1.125     ng       3726: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3727: 	if (selval[1].selected || selval[2].selected) {
                   3728: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3729: 	    if (selval[2].selected) {
                   3730: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3731: 	    }
1.269     raeburn  3732:         }
1.42      ng       3733:     }
                   3734: 
                   3735:     function resetEntry(numpart) {
                   3736: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3737: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3738: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3739: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3740: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3741: 	    for (var i=0; i<radioButton.length; i++) {
                   3742: 		radioButton[i].checked=false;
                   3743: 
                   3744: 	    }
                   3745: 	    textbox.value = "";
                   3746: 	    selval[0].selected = true;
                   3747: 
                   3748: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3749: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3750: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3751: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3752: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3753: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3754: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3755: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3756: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3757: 		if (saveselval == "excused") {
1.43      ng       3758: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3759: 		} else {
1.43      ng       3760: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3761: 		}
                   3762: 	    }
1.41      ng       3763: 	}
1.42      ng       3764:     }
                   3765: 
1.41      ng       3766: VIEWJAVASCRIPT
1.42      ng       3767: }
                   3768: 
1.44      ng       3769: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3770: sub viewgrades {
1.608     www      3771:     my ($request,$symb) = @_;
1.745     raeburn  3772:     my ($is_tool,$toolsymb);
                   3773:     if ($symb =~ /ext\.tool$/) {
                   3774:         $is_tool = 1;
                   3775:         $toolsymb = $symb;
                   3776:     }
1.42      ng       3777:     &viewgrades_js($request);
1.41      ng       3778: 
1.168     albertel 3779:     #need to make sure we have the correct data for later EXT calls, 
                   3780:     #thus invalidate the cache
                   3781:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3782:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3783:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3784:     &Apache::lonnet::clear_EXT_cache_status();
                   3785: 
1.398     albertel 3786:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3787: 
                   3788:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3789:     $result.=&jscriptNform($symb);
1.41      ng       3790: 
1.44      ng       3791:     #beginning of class grading form
1.442     banghart 3792:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3793:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3794: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3795: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3796: 	&build_section_inputs().
1.442     banghart 3797: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3798: 
1.738     raeburn  3799:     #retrieve selected groups
                   3800:     my (@groups,$group_display);
                   3801:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3802:     if (grep(/^all$/,@groups)) {
                   3803:         @groups = ('all');
                   3804:     } elsif (grep(/^none$/,@groups)) {
                   3805:         @groups = ('none');
                   3806:     } elsif (@groups > 0) {
                   3807:         $group_display = join(', ',@groups);
                   3808:     }
                   3809: 
                   3810:     my ($common_header,$specific_header,@sections,$section_display);
                   3811:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3812:     if (grep(/^all$/,@sections)) {
                   3813:         @sections = ('all');
                   3814:         if ($group_display) {
                   3815:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3816:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3817:         } elsif (grep(/^none$/,@groups)) {
                   3818:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3819:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3820:         } else {
                   3821: 	    $common_header = &mt('Assign Common Grade to Class');
                   3822:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3823:         }
                   3824:     } elsif (grep(/^none$/,@sections)) {
                   3825:         @sections = ('none');
                   3826:         if ($group_display) {
                   3827:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3828:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3829:         } elsif (grep(/^none$/,@groups)) {
                   3830:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3831:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3832:         } else {
                   3833:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3834: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3835:         }
                   3836:     } else {
                   3837:         $section_display = join (", ",@sections);
                   3838:         if ($group_display) {
                   3839:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3840:                                  $section_display,$group_display);
                   3841:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3842:                                    $section_display,$group_display);
                   3843:         } elsif (grep(/^none$/,@groups)) {
                   3844:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3845:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3846:         } else {
                   3847:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3848: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3849:         }
                   3850:     }
                   3851:     my %submit_types = &substatus_options();
                   3852:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3853: 
                   3854:     if ($env{'form.submitonly'} eq 'all') {
                   3855:         $result.= '<h3>'.$common_header.'</h3>';
                   3856:     } else {
1.745     raeburn  3857:         my $text;
                   3858:         if ($is_tool) {
                   3859:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3860:         } else {
                   3861:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3862:         }
                   3863:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 3864:     }
1.738     raeburn  3865:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3866:     #radio buttons/text box for assigning points for a section or class.
                   3867:     #handles different parts of a problem
1.582     raeburn  3868:     my $res_error;
                   3869:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3870:     if ($res_error) {
                   3871:         return &navmap_errormsg();
                   3872:     }
1.42      ng       3873:     my %weight = ();
                   3874:     my $ctsparts = 0;
1.45      ng       3875:     my %seen = ();
1.745     raeburn  3876:     my @part_response_id;
                   3877:     if ($is_tool) {
                   3878:         @part_response_id = ([0,'']);
                   3879:     } else {
                   3880:         @part_response_id = &flatten_responseType($responseType);
                   3881:     }
1.375     albertel 3882:     foreach my $part_response_id (@part_response_id) {
                   3883:     	my ($partid,$respid) = @{ $part_response_id };
                   3884: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3885: 	next if $seen{$partid};
                   3886: 	$seen{$partid}++;
1.744     raeburn  3887: #	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3888: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3889: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3890: 
1.324     albertel 3891: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3892: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3893: 	my $ctr = 0;
1.42      ng       3894: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3895: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3896: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3897: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3898: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3899: 	    $ctr++;
                   3900: 	}
1.485     albertel 3901: 	$radio.='</tr></table>';
                   3902: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3903: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3904: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3905: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3906:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3907:             '<select name="SELVAL_'.$partid.'" '.
                   3908:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3909:                 $weight{$partid}.')"> '.
1.401     albertel 3910: 	    '<option selected="selected"> </option>'.
1.485     albertel 3911: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3912: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3913: 	    '</select></td>'.
                   3914:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3915: 	$line.='<input type="hidden" name="partid_'.
                   3916: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3917: 	$line.='<input type="hidden" name="weight_'.
                   3918: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3919: 
                   3920: 	$result.=
                   3921: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3922: 	    '<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 3923: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3924: 	$ctsparts++;
1.41      ng       3925:     }
1.474     albertel 3926:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3927: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3928:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3929: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3930: 
1.44      ng       3931:     #table listing all the students in a section/class
                   3932:     #header of table
1.738     raeburn  3933:     if ($env{'form.submitonly'} eq 'all') {
                   3934:         $result.= '<h3>'.$specific_header.'</h3>';
                   3935:     } else {
1.745     raeburn  3936:         my $text;
                   3937:         if ($is_tool) {
                   3938:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3939:         } else {
                   3940:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3941:         }
                   3942:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  3943:     }
                   3944:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3945: 	      &Apache::loncommon::start_data_table_header_row().
                   3946: 	      '<th>'.&mt('No.').'</th>'.
                   3947: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3948:     my $partserror;
                   3949:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3950:     if ($partserror) {
                   3951:         return &navmap_errormsg();
                   3952:     }
1.324     albertel 3953:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3954:     my @partids = ();
1.41      ng       3955:     foreach my $part (@parts) {
1.745     raeburn  3956: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  3957:         my $narrowtext = &mt('Tries');
                   3958: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  3959: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 3960: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3961:         push(@partids,$partid);
1.628     www      3962: #
                   3963: # FIXME: Looks like $display looks at English text
                   3964: #
1.324     albertel 3965: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3966: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3967: 	    $result.='<th>'.
1.697     bisitz   3968: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3969: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3970: 	    next;
1.485     albertel 3971: 	    
1.207     albertel 3972: 	} else {
1.485     albertel 3973: 	    if ($display =~ /Problem Status/) {
                   3974: 		my $grade_status_mt = &mt('Grade Status');
                   3975: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3976: 	    }
                   3977: 	    my $part_mt = &mt('Part:');
                   3978: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3979: 	}
1.485     albertel 3980: 
1.474     albertel 3981: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3982:     }
1.474     albertel 3983:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3984: 
1.270     albertel 3985:     my %last_resets = 
                   3986: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3987: 
1.41      ng       3988:     #get info for each student
1.44      ng       3989:     #list all the students - with points and grade status
1.738     raeburn  3990:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3991:     my $ctr = 0;
1.294     albertel 3992:     foreach (sort 
                   3993: 	     {
                   3994: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3995: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3996: 		 }
                   3997: 		 return $a cmp $b;
                   3998: 	     } (keys(%$fullname))) {
1.324     albertel 3999: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4000: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4001:     }
1.474     albertel 4002:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4003:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 4004:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   4005: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4006:     if ($ctr == 0) {
1.442     banghart 4007:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4008:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4009:                 '<span class="LC_warning">';
                   4010:         if ($env{'form.submitonly'} eq 'all') {
                   4011:             if (grep(/^all$/,@sections)) {
                   4012:                 if (grep(/^all$/,@groups)) {
                   4013:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4014:                                    $stu_status);
                   4015:                 } elsif (grep(/^none$/,@groups)) {
                   4016:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4017:                                    $stu_status); 
                   4018:                 } else {
                   4019:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4020:                                    $group_display,$stu_status);
                   4021:                 }
                   4022:             } elsif (grep(/^none$/,@sections)) {
                   4023:                 if (grep(/^all$/,@groups)) {
                   4024:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4025:                                    $stu_status);
                   4026:                 } elsif (grep(/^none$/,@groups)) {
                   4027:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4028:                                    $stu_status);
                   4029:                 } else {
                   4030:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4031:                                    $group_display,$stu_status);
                   4032:                 }
                   4033:             } else {
                   4034:                 if (grep(/^all$/,@groups)) {
                   4035:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4036:                                    $section_display,$stu_status);
                   4037:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4038:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4039:                                    $section_display,$stu_status);
                   4040:                 } else {
                   4041:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4042:                                    $section_display,$group_display,$stu_status);
                   4043:                 }
                   4044:             }
                   4045:         } else {
                   4046:             if (grep(/^all$/,@sections)) {
                   4047:                 if (grep(/^all$/,@groups)) {
                   4048:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4049:                                    $stu_status,$submission_status);
                   4050:                 } elsif (grep(/^none$/,@groups)) {
                   4051:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4052:                                    $stu_status,$submission_status);
                   4053:                 } else {
                   4054:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4055:                                    $group_display,$stu_status,$submission_status);
                   4056:                 }
                   4057:             } elsif (grep(/^none$/,@sections)) {
                   4058:                 if (grep(/^all$/,@groups)) {
                   4059:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4060:                                    $stu_status,$submission_status);
                   4061:                 } elsif (grep(/^none$/,@groups)) {
                   4062:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4063:                                    $stu_status,$submission_status);
                   4064:                 } else {
                   4065:                     $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.',
                   4066:                                    $group_display,$stu_status,$submission_status);
                   4067:                 }
                   4068:             } else {
                   4069:                 if (grep(/^all$/,@groups)) {
                   4070: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4071: 	                           $section_display,$stu_status,$submission_status);
                   4072:                 } elsif (grep(/^none$/,@groups)) {
                   4073:                     $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.',
                   4074:                                    $section_display,$stu_status,$submission_status);
                   4075:                 } else {
                   4076:                     $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.',
                   4077:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4078:                 }
                   4079:             }
                   4080:         }
                   4081: 	$result .= '</span><br />';
1.96      albertel 4082:     }
1.41      ng       4083:     return $result;
                   4084: }
                   4085: 
1.738     raeburn  4086: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4087: sub viewstudentgrade {
1.745     raeburn  4088:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4089:     my ($uname,$udom) = split(/:/,$student);
                   4090:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4091:     my $submitonly = $env{'form.submitonly'};
                   4092:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4093:         my %partstatus = ();
                   4094:         if (ref($parts) eq 'ARRAY') {
                   4095:             foreach my $apart (@{$parts}) {
                   4096:                 my ($part,$type) = &split_part_type($apart);
                   4097:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4098:                 $status = 'nothing' if ($status eq '');
                   4099:                 $partstatus{$part}      = $status;
                   4100:                 my $subkey = "resource.$part.submitted_by";
                   4101:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4102:             }
                   4103:             my $submitted = 0;
                   4104:             my $graded = 0;
                   4105:             my $incorrect = 0;
                   4106:             foreach my $key (keys(%partstatus)) {
                   4107:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4108:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4109:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4110: 
                   4111:                 my $partid = (split(/\./,$key))[1];
                   4112:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4113:                     $submitted = 0;
                   4114:                 }
                   4115:             }
                   4116:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4117:                                        $submitonly eq 'incorrect' ||
                   4118:                                        $submitonly eq 'graded'));
                   4119:             return if (!$graded && ($submitonly eq 'graded'));
                   4120:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4121:         }
                   4122:     }
                   4123:     if ($submitonly eq 'queued') {
                   4124:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4125:         my %queue_status =
                   4126:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4127:                                                     $udom,$uname);
                   4128:         return if (!defined($queue_status{'gradingqueue'}));
                   4129:     }
                   4130:     $$ctr++;
                   4131:     my %aggregates = ();
1.474     albertel 4132:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4133: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4134: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4135: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4136: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4137: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4138:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4139:     foreach my $apart (@$parts) {
                   4140: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4141: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4142:         $result.='<td align="center">';
1.269     raeburn  4143:         my ($aggtries,$totaltries);
                   4144:         unless (exists($aggregates{$part})) {
1.270     albertel 4145: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4146: 	    $aggtries = $totaltries;
1.269     raeburn  4147:             if ($$last_resets{$part}) {  
1.270     albertel 4148:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4149: 					   $part);
                   4150:             }
1.269     raeburn  4151:             $result.='<input type="hidden" name="'.
                   4152:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4153:             $result.='<input type="hidden" name="'.
                   4154:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4155:             $aggregates{$part} = 1;
                   4156:         }
1.41      ng       4157: 	if ($type eq 'awarded') {
1.320     albertel 4158: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4159: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4160: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4161: 	    $result.='<input type="text" name="'.
1.89      albertel 4162: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4163:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4164: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4165: 	} elsif ($type eq 'solved') {
                   4166: 	    my ($status,$foo)=split(/_/,$score,2);
                   4167: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4168: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4169: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4170: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4171: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4172:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4173: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4174: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4175: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4176: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4177: 	} else {
                   4178: 	    $result.='<input type="hidden" name="'.
                   4179: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4180: 		    "\n";
1.233     albertel 4181: 	    $result.='<input type="text" name="'.
1.122     ng       4182: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4183: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4184: 	}
                   4185:     }
1.474     albertel 4186:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4187:     return $result;
1.38      ng       4188: }
                   4189: 
1.44      ng       4190: #--- change scores for all the students in a section/class
                   4191: #    record does not get update if unchanged
1.38      ng       4192: sub editgrades {
1.608     www      4193:     my ($request,$symb) = @_;
1.745     raeburn  4194:     my $toolsymb;
                   4195:     if ($symb =~ /ext\.tool$/) {
                   4196:         $toolsymb = $symb;
                   4197:     }
1.41      ng       4198: 
1.433     banghart 4199:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4200:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.768     raeburn  4201:     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4202: 
1.477     albertel 4203:     my $result= &Apache::loncommon::start_data_table().
                   4204: 	&Apache::loncommon::start_data_table_header_row().
                   4205: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4206: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4207:     my %scoreptr = (
                   4208: 		    'correct'  =>'correct_by_override',
                   4209: 		    'incorrect'=>'incorrect_by_override',
                   4210: 		    'excused'  =>'excused',
                   4211: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4212:                     'credited' =>'credit_attempted',
1.43      ng       4213: 		    'nothing'  => '',
                   4214: 		    );
1.257     albertel 4215:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4216: 
1.44      ng       4217:     my (@partid);
                   4218:     my %weight = ();
1.54      albertel 4219:     my %columns = ();
1.44      ng       4220:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4221: 
1.582     raeburn  4222:     my $partserror;
                   4223:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4224:     if ($partserror) {
                   4225:         return &navmap_errormsg();
                   4226:     }
1.54      albertel 4227:     my $header;
1.257     albertel 4228:     while ($ctr < $env{'form.totalparts'}) {
                   4229: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4230: 	push(@partid,$partid);
1.257     albertel 4231: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4232: 	$ctr++;
1.54      albertel 4233:     }
1.324     albertel 4234:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4235:     my $totcolspan = 0;
1.54      albertel 4236:     foreach my $partid (@partid) {
1.478     albertel 4237: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4238: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4239: 	$columns{$partid}=2;
                   4240: 	foreach my $stores (@parts) {
                   4241: 	    my ($part,$type) = &split_part_type($stores);
                   4242: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4243: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4244: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4245: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4246:             my $narrowtext = &mt('Tries');
                   4247: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4248: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4249: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4250: 	    $columns{$partid}+=2;
                   4251: 	}
1.748     raeburn  4252:         $totcolspan += $columns{$partid};
1.54      albertel 4253:     }
                   4254:     foreach my $partid (@partid) {
1.324     albertel 4255: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4256: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4257: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4258: 	    '</th>';
1.54      albertel 4259: 
1.44      ng       4260:     }
1.477     albertel 4261:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4262: 	&Apache::loncommon::start_data_table_header_row().
                   4263: 	$header.
                   4264: 	&Apache::loncommon::end_data_table_header_row();
                   4265:     my @noupdate;
1.126     ng       4266:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4267:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4268: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4269: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4270: 	my %newrecord;
                   4271: 	my $updateflag = 0;
1.108     albertel 4272: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4273: 	my $canmodify = &canmodify($usec);
                   4274: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4275: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4276: 	if (!$canmodify) {
1.477     albertel 4277: 	    push(@noupdate,
1.748     raeburn  4278: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4279: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4280: 	    next;
                   4281: 	}
1.269     raeburn  4282:         my %aggregate = ();
                   4283:         my $aggregateflag = 0;
1.281     albertel 4284: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4285: 	foreach (@partid) {
1.257     albertel 4286: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4287: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4288: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4289: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4290: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4291: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4292: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4293: 	    my $score;
                   4294: 	    if ($partial eq '') {
1.257     albertel 4295: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4296: 	    } elsif ($partial > 0) {
                   4297: 		$score = 'correct_by_override';
                   4298: 	    } elsif ($partial == 0) {
                   4299: 		$score = 'incorrect_by_override';
                   4300: 	    }
1.257     albertel 4301: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4302: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4303: 
1.292     albertel 4304: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4305: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4306: 	    if ($dropMenu eq 'reset status' &&
                   4307: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4308: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4309: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4310: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4311: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4312: 		$updateflag = 1;
1.269     raeburn  4313:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4314:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4315:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4316:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4317:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4318:                     $aggregateflag = 1;
                   4319:                 }
1.139     albertel 4320: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4321: 		$updateflag = 1;
                   4322: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4323: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4324: 		$rec_update++;
1.125     ng       4325: 	    }
                   4326: 
1.93      albertel 4327: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4328: 		'<td align="center">'.$awarded.
                   4329: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4330: 
1.54      albertel 4331: 
                   4332: 	    my $partid=$_;
                   4333: 	    foreach my $stores (@parts) {
                   4334: 		my ($part,$type) = &split_part_type($stores);
                   4335: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4336: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4337: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4338: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4339: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4340: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4341: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4342: 		    $updateflag=1;
                   4343: 		}
1.93      albertel 4344: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4345: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4346: 	    }
1.44      ng       4347: 	}
1.477     albertel 4348: 	$line.="\n";
1.301     albertel 4349: 
                   4350: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4351: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4352: 
1.44      ng       4353: 	if ($updateflag) {
                   4354: 	    $count++;
1.257     albertel 4355: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4356: 				    $udom,$uname);
1.301     albertel 4357: 
                   4358: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4359: 					      $cnum,$udom,$uname)) {
                   4360: 		# need to figure out if should be in queue.
                   4361: 		my %record =  
                   4362: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4363: 					     $udom,$uname);
                   4364: 		my $all_graded = 1;
                   4365: 		my $none_graded = 1;
                   4366: 		foreach my $part (@parts) {
                   4367: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4368: 			$all_graded = 0;
                   4369: 		    } else {
                   4370: 			$none_graded = 0;
                   4371: 		    }
                   4372: 		}
                   4373: 
                   4374: 		if ($all_graded || $none_graded) {
                   4375: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4376: 							   $symb,$cdom,$cnum,
                   4377: 							   $udom,$uname);
                   4378: 		}
                   4379: 	    }
                   4380: 
1.477     albertel 4381: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4382: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4383: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4384: 	    $updateCtr++;
1.93      albertel 4385: 	} else {
1.477     albertel 4386: 	    push(@noupdate,
                   4387: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4388: 	    $noupdateCtr++;
1.44      ng       4389: 	}
1.269     raeburn  4390:         if ($aggregateflag) {
                   4391:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4392: 				  $cdom,$cnum);
1.269     raeburn  4393:         }
1.93      albertel 4394:     }
1.477     albertel 4395:     if (@noupdate) {
1.748     raeburn  4396:         my $numcols=$totcolspan+2;
1.477     albertel 4397: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4398: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4399: 	    &mt('No Changes Occurred For the Students Below').
                   4400: 	    '</td>'.
1.477     albertel 4401: 	    &Apache::loncommon::end_data_table_row();
                   4402: 	foreach my $line (@noupdate) {
                   4403: 	    $result.=
                   4404: 		&Apache::loncommon::start_data_table_row().
                   4405: 		$line.
                   4406: 		&Apache::loncommon::end_data_table_row();
                   4407: 	}
1.44      ng       4408:     }
1.614     www      4409:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4410:     my $msg = '<p><b>'.
                   4411: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4412: 	    $rec_update,$count).'</b><br />'.
                   4413: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4414: 	'</b></p>';
1.44      ng       4415:     return $title.$msg.$result;
1.5       albertel 4416: }
1.54      albertel 4417: 
                   4418: sub split_part_type {
                   4419:     my ($partstr) = @_;
                   4420:     my ($temp,@allparts)=split(/_/,$partstr);
                   4421:     my $type=pop(@allparts);
1.439     albertel 4422:     my $part=join('_',@allparts);
1.54      albertel 4423:     return ($part,$type);
                   4424: }
                   4425: 
1.44      ng       4426: #------------- end of section for handling grading by section/class ---------
                   4427: #
                   4428: #----------------------------------------------------------------------------
                   4429: 
1.5       albertel 4430: 
1.44      ng       4431: #----------------------------------------------------------------------------
                   4432: #
                   4433: #-------------------------- Next few routines handles grading by csv upload
                   4434: #
                   4435: #--- Javascript to handle csv upload
1.27      albertel 4436: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4437:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4438:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4439:   &js_escape(\$error1);
                   4440:   &js_escape(\$error2);
1.27      albertel 4441:   return(<<ENDPICK);
                   4442:   function verify(vf) {
                   4443:     var foundsomething=0;
                   4444:     var founduname=0;
1.243     albertel 4445:     var foundID=0;
1.743     raeburn  4446:     var foundclicker=0;
1.27      albertel 4447:     for (i=0;i<=vf.nfields.value;i++) {
                   4448:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4449:       if (i==0 && tw!=0) { foundID=1; }
                   4450:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4451:       if (i==2 && tw!=0) { foundclicker=1; }
                   4452:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4453:     }
1.743     raeburn  4454:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4455: 	alert('$error1');
                   4456: 	return;
1.27      albertel 4457:     }
                   4458:     if (foundsomething==0) {
1.246     albertel 4459: 	alert('$error2');
                   4460: 	return;
1.27      albertel 4461:     }
                   4462:     vf.submit();
                   4463:   }
                   4464:   function flip(vf,tf) {
                   4465:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4466:     var i;
                   4467:     for (i=0;i<=vf.nfields.value;i++) {
                   4468:       //can not pick the same destination field for both name and domain
                   4469:       if (((i ==0)||(i ==1)) && 
                   4470:           ((tf==0)||(tf==1)) && 
                   4471:           (i!=tf) &&
                   4472:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4473:         eval('vf.f'+i+'.selectedIndex=0;')
                   4474:       }
                   4475:     }
                   4476:   }
                   4477: ENDPICK
                   4478: }
                   4479: 
                   4480: sub csvupload_javascript_forward_associate {
1.743     raeburn  4481:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4482:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4483:   &js_escape(\$error1);
                   4484:   &js_escape(\$error2);
1.27      albertel 4485:   return(<<ENDPICK);
                   4486:   function verify(vf) {
                   4487:     var foundsomething=0;
                   4488:     var founduname=0;
1.243     albertel 4489:     var foundID=0;
1.743     raeburn  4490:     var foundclicker=0;
1.27      albertel 4491:     for (i=0;i<=vf.nfields.value;i++) {
                   4492:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4493:       if (tw==1) { foundID=1; }
                   4494:       if (tw==2) { founduname=1; }
1.745     raeburn  4495:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4496:       if (tw>4) { foundsomething=1; }
1.27      albertel 4497:     }
1.743     raeburn  4498:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4499: 	alert('$error1');
                   4500: 	return;
1.27      albertel 4501:     }
                   4502:     if (foundsomething==0) {
1.246     albertel 4503: 	alert('$error2');
                   4504: 	return;
1.27      albertel 4505:     }
                   4506:     vf.submit();
                   4507:   }
                   4508:   function flip(vf,tf) {
                   4509:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4510:     var i;
                   4511:     //can not pick the same destination field twice
                   4512:     for (i=0;i<=vf.nfields.value;i++) {
                   4513:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4514:         eval('vf.f'+i+'.selectedIndex=0;')
                   4515:       }
                   4516:     }
                   4517:   }
                   4518: ENDPICK
                   4519: }
                   4520: 
1.26      albertel 4521: sub csvuploadmap_header {
1.324     albertel 4522:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4523:     my $javascript;
1.257     albertel 4524:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4525: 	$javascript=&csvupload_javascript_reverse_associate();
                   4526:     } else {
                   4527: 	$javascript=&csvupload_javascript_forward_associate();
                   4528:     }
1.45      ng       4529: 
1.418     albertel 4530:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4531:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4532:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4533:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4534:     my $reverse=&mt("Reverse Association");
1.41      ng       4535:     $request->print(<<ENDPICK);
1.632     www      4536: <br />
                   4537: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4538: <input type="hidden" name="associate"  value="" />
                   4539: <input type="hidden" name="phase"      value="three" />
                   4540: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4541: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4542: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4543: <input type="hidden" name="upfile_associate" 
1.257     albertel 4544:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4545: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4546: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4547: <hr />
                   4548: ENDPICK
1.597     wenzelju 4549:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4550:     return '';
1.26      albertel 4551: 
                   4552: }
                   4553: 
                   4554: sub csvupload_fields {
1.582     raeburn  4555:     my ($symb,$errorref) = @_;
1.745     raeburn  4556:     my $toolsymb;
                   4557:     if ($symb =~ /ext\.tool$/) {
                   4558:         $toolsymb = $symb;
                   4559:     }
1.582     raeburn  4560:     my (@parts) = &getpartlist($symb,$errorref);
                   4561:     if (ref($errorref)) {
                   4562:         if ($$errorref) {
                   4563:             return;
                   4564:         }
                   4565:     }
                   4566: 
1.556     weissno  4567:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4568: 		['username','Student Username'],
1.743     raeburn  4569: 		['clicker','Clicker ID'],
1.243     albertel 4570: 		['domain','Student Domain']);
1.324     albertel 4571:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4572:     foreach my $part (sort(@parts)) {
                   4573: 	my @datum;
1.745     raeburn  4574: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4575: 	my $name=$part;
1.745     raeburn  4576: 	if (!$display) { $display = $name; }
1.41      ng       4577: 	@datum=($name,$display);
1.244     albertel 4578: 	if ($name=~/^stores_(.*)_awarded/) {
                   4579: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4580: 	}
1.41      ng       4581: 	push(@fields,\@datum);
                   4582:     }
                   4583:     return (@fields);
1.26      albertel 4584: }
                   4585: 
                   4586: sub csvuploadmap_footer {
1.41      ng       4587:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4588:     my $buttontext = &mt('Assign Grades');
1.41      ng       4589:     $request->print(<<ENDPICK);
1.26      albertel 4590: </table>
                   4591: <input type="hidden" name="nfields" value="$i" />
                   4592: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4593: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4594: </form>
                   4595: ENDPICK
                   4596: }
                   4597: 
1.283     albertel 4598: sub checkforfile_js {
1.638     www      4599:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4600:     &js_escape(\$alertmsg);
1.597     wenzelju 4601:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4602:     function checkUpload(formname) {
                   4603: 	if (formname.upfile.value == "") {
1.539     riegler  4604: 	    alert("$alertmsg");
1.86      ng       4605: 	    return false;
                   4606: 	}
                   4607: 	formname.submit();
                   4608:     }
                   4609: CSVFORMJS
1.283     albertel 4610:     return $result;
                   4611: }
                   4612: 
                   4613: sub upcsvScores_form {
1.608     www      4614:     my ($request,$symb) = @_;
1.283     albertel 4615:     if (!$symb) {return '';}
                   4616:     my $result=&checkforfile_js();
1.632     www      4617:     $result.=&Apache::loncommon::start_data_table().
                   4618:              &Apache::loncommon::start_data_table_header_row().
                   4619:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4620:              &Apache::loncommon::end_data_table_header_row().
                   4621:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4622:     my $upload=&mt("Upload Scores");
1.86      ng       4623:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4624:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4625:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4626:     $result.=<<ENDUPFORM;
1.106     albertel 4627: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4628: <input type="hidden" name="symb" value="$symb" />
                   4629: <input type="hidden" name="command" value="csvuploadmap" />
                   4630: $upfile_select
1.589     bisitz   4631: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4632: </form>
                   4633: ENDUPFORM
1.370     www      4634:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4635:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4636:              '</td>'.
                   4637:             &Apache::loncommon::end_data_table_row().
                   4638:             &Apache::loncommon::end_data_table();
1.86      ng       4639:     return $result;
                   4640: }
                   4641: 
                   4642: 
1.26      albertel 4643: sub csvuploadmap {
1.768     raeburn  4644:     my ($request,$symb) = @_;
1.41      ng       4645:     if (!$symb) {return '';}
1.72      ng       4646: 
1.41      ng       4647:     my $datatoken;
1.257     albertel 4648:     if (!$env{'form.datatoken'}) {
1.41      ng       4649: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4650:     } else {
1.742     raeburn  4651: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4652:         if ($datatoken ne '') {
                   4653: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4654:         }
1.26      albertel 4655:     }
1.41      ng       4656:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4657:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4658:     my ($i,$keyfields);
                   4659:     if (@records) {
1.582     raeburn  4660:         my $fieldserror;
                   4661: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4662:         if ($fieldserror) {
                   4663:             $request->print(&navmap_errormsg());
                   4664:             return;
                   4665:         }
1.257     albertel 4666: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4667: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4668: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4669: 							  \@fields);
                   4670: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4671: 	    chop($keyfields);
                   4672: 	} else {
                   4673: 	    unshift(@fields,['none','']);
                   4674: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4675: 							    \@fields);
1.311     banghart 4676:             foreach my $rec (@records) {
                   4677:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4678:                 if (%temp) {
                   4679:                     $keyfields=join(',',sort(keys(%temp)));
                   4680:                     last;
                   4681:                 }
                   4682:             }
1.41      ng       4683: 	}
                   4684:     }
                   4685:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4686: 
1.41      ng       4687:     return '';
1.27      albertel 4688: }
                   4689: 
1.246     albertel 4690: sub csvuploadoptions {
1.608     www      4691:     my ($request,$symb)= @_;
1.632     www      4692:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4693:     $request->print(<<ENDPICK);
                   4694: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4695: <input type="hidden" name="command"    value="csvuploadassign" />
                   4696: <p>
                   4697: <label>
                   4698:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4699:    $overwrite
1.246     albertel 4700: </label>
                   4701: </p>
                   4702: ENDPICK
                   4703:     my %fields=&get_fields();
                   4704:     if (!defined($fields{'domain'})) {
1.257     albertel 4705: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4706: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4707:     }
1.257     albertel 4708:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4709: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4710: 	my $cleankey=$1;
                   4711: 	if ($cleankey eq 'command') { next; }
                   4712: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4713: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4714:     }
                   4715:     # FIXME do a check for any duplicated user ids...
                   4716:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4717:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4718: <hr /></form>'."\n");
1.246     albertel 4719:     return '';
                   4720: }
                   4721: 
                   4722: sub get_fields {
                   4723:     my %fields;
1.257     albertel 4724:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4725:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4726: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4727: 	    if ($env{'form.f'.$i} ne 'none') {
                   4728: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4729: 	    }
                   4730: 	} else {
1.257     albertel 4731: 	    if ($env{'form.f'.$i} ne 'none') {
                   4732: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4733: 	    }
                   4734: 	}
1.27      albertel 4735:     }
1.246     albertel 4736:     return %fields;
                   4737: }
                   4738: 
                   4739: sub csvuploadassign {
1.766     raeburn  4740:     my ($request,$symb) = @_;
1.246     albertel 4741:     if (!$symb) {return '';}
1.345     bowersj2 4742:     my $error_msg = '';
1.742     raeburn  4743:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4744:     if ($datatoken ne '') { 
                   4745:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4746:     }
1.246     albertel 4747:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4748:     my %fields=&get_fields();
1.257     albertel 4749:     my $courseid=$env{'request.course.id'};
1.97      albertel 4750:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4751:     my @notallowed;
1.41      ng       4752:     my @skipped;
1.657     raeburn  4753:     my @warnings;
1.41      ng       4754:     my $countdone=0;
                   4755:     foreach my $grade (@gradedata) {
                   4756: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4757: 	my $domain;
                   4758: 	if ($entries{$fields{'domain'}}) {
                   4759: 	    $domain=$entries{$fields{'domain'}};
                   4760: 	} else {
1.257     albertel 4761: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4762: 	}
1.243     albertel 4763: 	$domain=~s/\s//g;
1.41      ng       4764: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4765: 	$username=~s/\s//g;
1.243     albertel 4766: 	if (!$username) {
                   4767: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4768: 	    $id=~s/\s//g;
1.737     raeburn  4769:             if ($id ne '') {
                   4770: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4771: 	        $username=$ids{$id};
                   4772:             } else {
                   4773:                 if ($entries{$fields{'clicker'}}) {
                   4774:                     my $clicker = $entries{$fields{'clicker'}};
                   4775:                     $clicker=~s/\s//g;
                   4776:                     if ($clicker ne '') {
                   4777:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4778:                         if ($clickers{$clicker} ne '') {  
                   4779:                             my $match = 0;
                   4780:                             my @inclass;
                   4781:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4782:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4783:                                     $username = $poss;
                   4784:                                     push(@inclass,$poss);
                   4785:                                     $match ++;
                   4786:                                     
                   4787:                                 }
                   4788:                             }
                   4789:                             if ($match > 1) {
                   4790:                                 undef($username); 
                   4791:                                 $request->print('<p class="LC_warning">'.
                   4792:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4793:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4794:                             }
                   4795:                         }
                   4796:                     }
                   4797:                 }
                   4798:             }
1.243     albertel 4799: 	}
1.41      ng       4800: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4801: 	    my $id=$entries{$fields{'ID'}};
                   4802: 	    $id=~s/\s//g;
1.737     raeburn  4803:             my $clicker = $entries{$fields{'clicker'}};
                   4804:             $clicker=~s/\s//g;
                   4805:             if ($clicker) {
                   4806:                 push(@skipped,"$clicker:$domain");
                   4807: 	    } elsif ($id) {
1.247     albertel 4808: 		push(@skipped,"$id:$domain");
                   4809: 	    } else {
                   4810: 		push(@skipped,"$username:$domain");
                   4811: 	    }
1.41      ng       4812: 	    next;
                   4813: 	}
1.108     albertel 4814: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4815: 	if (!&canmodify($usec)) {
                   4816: 	    push(@notallowed,"$username:$domain");
                   4817: 	    next;
                   4818: 	}
1.244     albertel 4819: 	my %points;
1.41      ng       4820: 	my %grades;
                   4821: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4822: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4823: 		$dest eq 'domain') { next; }
                   4824: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4825: 	    if ($dest=~/stores_(.*)_points/) {
                   4826: 		my $part=$1;
                   4827: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4828: 					      $symb,$domain,$username);
1.345     bowersj2 4829:                 if ($wgt) {
                   4830:                     $entries{$fields{$dest}}=~s/\s//g;
                   4831:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4832:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4833:                                           : 'correct_by_override';
1.638     www      4834:                     if ($pcr>1) {
1.657     raeburn  4835:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4836:                     }
1.345     bowersj2 4837:                     $grades{"resource.$part.awarded"}=$pcr;
                   4838:                     $grades{"resource.$part.solved"}=$award;
                   4839:                     $points{$part}=1;
                   4840:                 } else {
                   4841:                     $error_msg = "<br />" .
                   4842:                         &mt("Some point values were assigned"
                   4843:                             ." for problems with a weight "
                   4844:                             ."of zero. These values were "
                   4845:                             ."ignored.");
                   4846:                 }
1.244     albertel 4847: 	    } else {
                   4848: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4849: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4850: 		my $store_key=$dest;
                   4851: 		$store_key=~s/^stores/resource/;
                   4852: 		$store_key=~s/_/\./g;
                   4853: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4854: 	    }
1.41      ng       4855: 	}
1.766     raeburn  4856: 	if (! %grades) {
1.508     www      4857:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4858:         } else {
                   4859: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4860: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4861: 					   $env{'request.course.id'},
                   4862: 					   $domain,$username);
1.508     www      4863: 	   if ($result eq 'ok') {
1.627     www      4864: # Successfully stored
1.508     www      4865: 	      $request->print('.');
1.627     www      4866: # Remove from grading queue
                   4867:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4868:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4869:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4870:                                              $domain,$username);
                   4871:               $countdone++;
                   4872:            } else {
1.508     www      4873: 	      $request->print("<p><span class=\"LC_error\">".
                   4874:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4875:                                   "$username:$domain",$result)."</span></p>");
                   4876: 	   }
                   4877: 	   $request->rflush();
                   4878:         }
1.41      ng       4879:     }
1.570     www      4880:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4881:     if (@warnings) {
                   4882:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4883:         $request->print(join(', ',@warnings));
                   4884:     }
1.41      ng       4885:     if (@skipped) {
1.571     www      4886: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4887:         $request->print(join(', ',@skipped));
1.106     albertel 4888:     }
                   4889:     if (@notallowed) {
1.571     www      4890: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4891: 	$request->print(join(', ',@notallowed));
1.41      ng       4892:     }
1.106     albertel 4893:     $request->print("<br />\n");
1.345     bowersj2 4894:     return $error_msg;
1.26      albertel 4895: }
1.44      ng       4896: #------------- end of section for handling csv file upload ---------
                   4897: #
                   4898: #-------------------------------------------------------------------
                   4899: #
1.122     ng       4900: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4901: #
                   4902: #--- Select a page/sequence and a student to grade
1.68      ng       4903: sub pickStudentPage {
1.608     www      4904:     my ($request,$symb) = @_;
1.68      ng       4905: 
1.539     riegler  4906:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  4907:     &js_escape(\$alertmsg);
1.597     wenzelju 4908:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4909: 
                   4910: function checkPickOne(formname) {
1.76      ng       4911:     if (radioSelection(formname.student) == null) {
1.539     riegler  4912: 	alert("$alertmsg");
1.68      ng       4913: 	return;
                   4914:     }
1.125     ng       4915:     ptr = pullDownSelection(formname.selectpage);
                   4916:     formname.page.value = formname["page"+ptr].value;
                   4917:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4918:     formname.submit();
                   4919: }
                   4920: 
                   4921: LISTJAVASCRIPT
1.118     ng       4922:     &commonJSfunctions($request);
1.608     www      4923: 
1.257     albertel 4924:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4925:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4926:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761     raeburn  4927:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       4928: 
1.398     albertel 4929:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4930: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4931: 
1.80      ng       4932:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4933:     my $map_error;
                   4934:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4935:     if ($map_error) {
                   4936:         $request->print(&navmap_errormsg());
                   4937:         return; 
                   4938:     }
1.137     albertel 4939:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4940: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4941: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4942: 
                   4943:     # Collection of hidden fields
1.70      ng       4944:     my $ctr=0;
1.68      ng       4945:     foreach (@$titles) {
1.700     bisitz   4946:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4947:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4948:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4949:         $ctr++;
1.68      ng       4950:     }
1.700     bisitz   4951:     $result.='<input type="hidden" name="page" />'."\n".
                   4952:         '<input type="hidden" name="title" />'."\n";
                   4953: 
                   4954:     $result.=&build_section_inputs();
                   4955:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4956:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4957: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4958: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4959: 
1.700     bisitz   4960:     # Show grading options
                   4961:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4962:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4963:     $ctr=0;
                   4964:     foreach (@$titles) {
                   4965: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4966: 	$select.='<option value="'.$ctr.'"'.
                   4967: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4968: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4969: 	$ctr++;
                   4970:     }
1.700     bisitz   4971:     $select.= '</select>';
1.68      ng       4972: 
1.700     bisitz   4973:     $result.=
                   4974:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4975:        .$select
                   4976:        .&Apache::lonhtmlcommon::row_closure();
                   4977: 
                   4978:     $result.=
                   4979:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4980:        .'<label><input type="radio" name="vProb" value="no"'
                   4981:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4982:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4983:            .&mt('yes').'</label>'."\n"
                   4984:        .&Apache::lonhtmlcommon::row_closure();
                   4985: 
                   4986:     $result.=
                   4987:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4988:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4989:            .&mt('none').' </label>'."\n"
                   4990:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4991:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4992:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4993:            .&mt('all submissions with details').' </label>'
                   4994:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4995:     
1.700     bisitz   4996:     $result.=
                   4997:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4998:        .'<input type="text" name="CODE" value="" />'
                   4999:        .&Apache::lonhtmlcommon::row_closure(1)
                   5000:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5001: 
1.700     bisitz   5002:     # Show list of students to select for grading
                   5003:     $result.='<br /><input type="button" '.
1.589     bisitz   5004:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5005: 
1.68      ng       5006:     $request->print($result);
                   5007: 
1.485     albertel 5008:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5009: 	&Apache::loncommon::start_data_table().
                   5010: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5011: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5012: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5013: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5014: 	'<th>'.&nameUserString('header').'</th>'.
                   5015: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5016:  
1.761     raeburn  5017:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5018:     my $ptr = 1;
1.294     albertel 5019:     foreach my $student (sort 
                   5020: 			 {
                   5021: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5022: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5023: 			     }
                   5024: 			     return $a cmp $b;
                   5025: 			 } (keys(%$fullname))) {
1.68      ng       5026: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5027: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5028:                                   : '</td>');
1.126     ng       5029: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5030: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5031: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5032: 	$studentTable.=
                   5033: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5034:                          : '');
1.68      ng       5035: 	$ptr++;
                   5036:     }
1.484     albertel 5037:     if ($ptr%2 == 0) {
                   5038: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5039: 	    &Apache::loncommon::end_data_table_row();
                   5040:     }
                   5041:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5042:     $studentTable.='<input type="button" '.
1.589     bisitz   5043:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5044: 
                   5045:     $request->print($studentTable);
                   5046: 
                   5047:     return '';
                   5048: }
                   5049: 
                   5050: sub getSymbMap {
1.582     raeburn  5051:     my ($map_error) = @_;
1.132     bowersj2 5052:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5053:     unless (ref($navmap)) {
                   5054:         if (ref($map_error)) {
                   5055:             $$map_error = 'navmap';
                   5056:         }
                   5057:         return;
                   5058:     }
1.68      ng       5059:     my %symbx = ();
                   5060:     my @titles = ();
1.117     bowersj2 5061:     my $minder = 0;
                   5062: 
                   5063:     # Gather every sequence that has problems.
1.240     albertel 5064:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5065: 					       1,0,1);
1.117     bowersj2 5066:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5067: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5068: 	    my $title = $minder.'.'.
                   5069: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5070: 	    push(@titles, $title); # minder in case two titles are identical
                   5071: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5072: 	    $minder++;
1.241     albertel 5073: 	}
1.68      ng       5074:     }
                   5075:     return \@titles,\%symbx;
                   5076: }
                   5077: 
1.72      ng       5078: #
                   5079: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5080: sub displayPage {
1.608     www      5081:     my ($request,$symb) = @_;
1.257     albertel 5082:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5083:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5084:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5085:     my $pageTitle = $env{'form.page'};
1.103     albertel 5086:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5087:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5088:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5089: 
                   5090:     #need to make sure we have the correct data for later EXT calls, 
                   5091:     #thus invalidate the cache
                   5092:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5093:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5094:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5095:     &Apache::lonnet::clear_EXT_cache_status();
                   5096: 
1.103     albertel 5097:     if (!&canview($usec)) {
1.712     bisitz   5098:         $request->print(
                   5099:             '<span class="LC_warning">'.
                   5100:             &mt('Unable to view requested student. ([_1])',
                   5101:                     $env{'form.student'}).
                   5102:             '</span>');
                   5103:         return;
1.103     albertel 5104:     }
1.398     albertel 5105:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5106:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5107: 	'</h3>'."\n";
1.500     albertel 5108:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5109:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5110: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5111:     } else {
                   5112: 	delete($env{'form.CODE'});
                   5113:     }
1.71      ng       5114:     &sub_page_js($request);
                   5115:     $request->print($result);
                   5116: 
1.132     bowersj2 5117:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5118:     unless (ref($navmap)) {
                   5119:         $request->print(&navmap_errormsg());
                   5120:         return;
                   5121:     }
1.257     albertel 5122:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5123:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5124:     if (!$map) {
1.485     albertel 5125: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5126: 	return; 
                   5127:     }
1.68      ng       5128:     my $iterator = $navmap->getIterator($map->map_start(),
                   5129: 					$map->map_finish());
                   5130: 
1.71      ng       5131:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5132: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5133: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5134: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5135: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5136: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5137: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5138: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5139: 
1.382     albertel 5140:     if (defined($env{'form.CODE'})) {
                   5141: 	$studentTable.=
                   5142: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5143:     }
1.381     albertel 5144:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5145: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5146: 
1.594     bisitz   5147:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5148:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5149:         '</span>'."\n".
1.484     albertel 5150: 	&Apache::loncommon::start_data_table().
                   5151: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5152: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5153: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5154: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5155: 
1.329     albertel 5156:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5157:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5158:     $iterator->next(); # skip the first BEGIN_MAP
                   5159:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5160:     while ($depth > 0) {
1.68      ng       5161:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5162:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5163: 
1.745     raeburn  5164:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5165: 	    my $parts = $curRes->parts();
1.68      ng       5166:             my $title = $curRes->compTitle();
1.71      ng       5167: 	    my $symbx = $curRes->symb();
1.746     raeburn  5168:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5169: 	    $studentTable.=
                   5170: 		&Apache::loncommon::start_data_table_row().
                   5171: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5172: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5173: 		                        : '<br />('.&mt('[_1]parts',
                   5174: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5175: 		 ).
                   5176: 		 '</td>';
1.71      ng       5177: 	    $studentTable.='<td valign="top">';
1.382     albertel 5178: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5179:             if ($is_tool) {
                   5180:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5181:             } else {
1.745     raeburn  5182: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5183: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5184: 					         undef,'both',\%form);
                   5185: 	        } else {
                   5186: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5187: 		    $companswer =~ s|<form(.*?)>||g;
                   5188: 		    $companswer =~ s|</form>||g;
                   5189: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5190: #		        $companswer =~ s/$1/ /ms;
                   5191: #		        $request->print('match='.$1."<br />\n");
                   5192: #		    }
                   5193: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5194: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5195: 		}
1.71      ng       5196: 	    }
                   5197: 
1.257     albertel 5198: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5199: 
1.257     albertel 5200: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5201: 		if ($record{'version'} eq '') {
1.745     raeburn  5202:                     my $msg = &mt('No recorded submission for this problem.');
                   5203:                     if ($is_tool) {
                   5204:                         $msg = &mt('No recorded transactions for this external tool');
                   5205:                     }
                   5206: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5207: 		} else {
1.116     ng       5208: 		    my %responseType = ();
                   5209: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5210: 			my @responseIds =$curRes->responseIds($partid);
                   5211: 			my @responseType =$curRes->responseType($partid);
                   5212: 			my %responseIds;
                   5213: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5214: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5215: 			}
                   5216: 			$responseType{$partid} = \%responseIds;
1.116     ng       5217: 		    }
1.148     albertel 5218: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5219: 		}
1.257     albertel 5220: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5221: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5222:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5223: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5224: 									$env{'request.course.id'},
1.726     raeburn  5225: 									'','.submission',undef,
                   5226:                                                                         $usec,$identifier);
1.71      ng       5227:  
                   5228: 	    }
1.103     albertel 5229: 	    if (&canmodify($usec)) {
1.585     bisitz   5230:             $studentTable.=&gradeBox_start();
1.103     albertel 5231: 		foreach my $partid (@{$parts}) {
                   5232: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5233: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5234: 		    $question++;
                   5235: 		}
1.585     bisitz   5236:             $studentTable.=&gradeBox_end();
1.196     albertel 5237: 		$prob++;
1.71      ng       5238: 	    }
                   5239: 	    $studentTable.='</td></tr>';
1.68      ng       5240: 
1.103     albertel 5241: 	}
1.68      ng       5242:         $curRes = $iterator->next();
                   5243:     }
                   5244: 
1.589     bisitz   5245:     $studentTable.=
                   5246:         '</table>'."\n".
                   5247:         '<input type="button" value="'.&mt('Save').'" '.
                   5248:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5249:         '</form>'."\n";
1.71      ng       5250:     $request->print($studentTable);
                   5251: 
                   5252:     return '';
1.119     ng       5253: }
                   5254: 
                   5255: sub displaySubByDates {
1.148     albertel 5256:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5257:     my $isCODE=0;
1.335     albertel 5258:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5259:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5260:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5261:     my $studentTable=&Apache::loncommon::start_data_table().
                   5262: 	&Apache::loncommon::start_data_table_header_row().
                   5263: 	'<th>'.&mt('Date/Time').'</th>'.
                   5264: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5265:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5266: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5267: 	'<th>'.&mt('Status').'</th>'.
                   5268: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5269:     my ($version);
                   5270:     my %mark;
1.148     albertel 5271:     my %orders;
1.119     ng       5272:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5273:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5274:         if ($is_tool) {
                   5275:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5276:         } else {
                   5277:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5278:         }
1.147     albertel 5279:     }
1.335     albertel 5280: 
                   5281:     my $interaction;
1.525     raeburn  5282:     my $no_increment = 1;
1.735     raeburn  5283:     my (%lastrndseed,%lasttype);
1.119     ng       5284:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5285: 	my $timestamp = 
                   5286: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5287: 	if (exists($$record{$version.':resource.0.version'})) {
                   5288: 	    $interaction = $$record{$version.':resource.0.version'};
                   5289: 	}
1.671     raeburn  5290:         if ($isTask && $env{'form.previousversion'}) {
                   5291:             next unless ($interaction == $env{'form.previousversion'});
                   5292:         }
1.335     albertel 5293: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5294: 		             : "$version:resource");
1.467     albertel 5295: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5296: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5297: 	if ($isCODE) {
                   5298: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5299: 	}
1.671     raeburn  5300:         if ($isTask) {
                   5301:             $studentTable.='<td>'.$interaction.'</td>';
                   5302:         }
1.119     ng       5303: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5304: 	my @displaySub = ();
                   5305: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5306:             my ($hidden,$type);
                   5307:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5308:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5309:                 $hidden = 1;
                   5310:             }
1.749     raeburn  5311:             my @matchKey;
                   5312:             if ($isTask) {
1.769     raeburn  5313:                 @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
1.749     raeburn  5314:             } elsif ($is_tool) {
1.769     raeburn  5315:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
1.749     raeburn  5316:             } else {
1.769     raeburn  5317:                 @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
1.749     raeburn  5318:             }
1.122     ng       5319: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5320: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5321: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5322: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5323: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5324:                     if ($is_tool) {
                   5325:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5326:                     } else {
1.749     raeburn  5327: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5328: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5329:                         $displaySub[0].='<span class="LC_nobreak">';
                   5330:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5331:                                        .' <span class="LC_internal_info">'
                   5332:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5333:                                        .'</span>'
                   5334:                                        .' <b>';
                   5335:                         if ($hidden) {
                   5336:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5337:                         } else {
                   5338:                             my ($trial,$rndseed,$newvariation);
                   5339:                             if ($type eq 'randomizetry') {
                   5340:                                 $trial = $$record{"$where.$partid.tries"};
                   5341:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5342:                             }
                   5343: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5344: 			        $displaySub[0].=&mt('Trial not counted');
                   5345: 		            } else {
                   5346: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5347: 					        $$record{"$where.$partid.tries"});
                   5348:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5349:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5350:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5351:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5352:                                     }
1.640     raeburn  5353:                                 }
1.749     raeburn  5354:                                 $lastrndseed{$partid} = $rndseed;
                   5355:                                 $lasttype{$partid} = $type;
                   5356: 		            }
                   5357: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5358:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5359: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5360: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5361: 			        $orders{$partid}->{$responseId}=
                   5362: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5363:                                                $no_increment,$type,$trial,$rndseed);
                   5364: 		            }
                   5365: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5366: 		            $displaySub[0].='&nbsp; '.
                   5367: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5368:                         }
1.596     raeburn  5369:                     }
1.147     albertel 5370: 		}
                   5371: 	    }
1.335     albertel 5372: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5373: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5374: 				    $$record{"$where.$partid.checkedin"},
                   5375: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5376: 					'<br />';
1.335     albertel 5377: 	    }
                   5378: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5379: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5380: 		    lc($$record{"$where.$partid.award"}).' '.
                   5381: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5382: 		    '<br />';
1.749     raeburn  5383: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5384: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5385: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5386: 		}
1.147     albertel 5387: 	    }
1.335     albertel 5388: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5389: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5390: 		unless ($is_tool) {
                   5391: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5392: 		}
1.335     albertel 5393: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5394: 		$displaySub[2].=
1.749     raeburn  5395: 		    $$record{"$version:resource.$partid.regrader"};
                   5396:                 unless ($is_tool) {
                   5397: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5398:                 }
1.147     albertel 5399: 	    }
                   5400: 	}
                   5401: 	# needed because old essay regrader has not parts info
                   5402: 	if (exists $$record{"$version:resource.regrader"}) {
                   5403: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5404: 	}
                   5405: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5406: 	if ($displaySub[2]) {
1.467     albertel 5407: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5408: 	}
1.467     albertel 5409: 	$studentTable.='&nbsp;</td>'.
                   5410: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5411:     }
1.467     albertel 5412:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5413:     return $studentTable;
1.71      ng       5414: }
                   5415: 
                   5416: sub updateGradeByPage {
1.608     www      5417:     my ($request,$symb) = @_;
1.71      ng       5418: 
1.257     albertel 5419:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5420:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5421:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5422:     my $pageTitle = $env{'form.page'};
1.103     albertel 5423:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5424:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5425:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5426:     if (!&canmodify($usec)) {
1.526     raeburn  5427: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5428: 	return;
                   5429:     }
1.398     albertel 5430:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5431:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5432: 	'</h3>'."\n";
1.70      ng       5433: 
1.68      ng       5434:     $request->print($result);
                   5435: 
1.582     raeburn  5436: 
1.132     bowersj2 5437:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5438:     unless (ref($navmap)) {
                   5439:         $request->print(&navmap_errormsg());
                   5440:         return;
                   5441:     }
1.257     albertel 5442:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5443:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5444:     if (!$map) {
1.527     raeburn  5445: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5446: 	return; 
                   5447:     }
1.71      ng       5448:     my $iterator = $navmap->getIterator($map->map_start(),
                   5449: 					$map->map_finish());
1.70      ng       5450: 
1.484     albertel 5451:     my $studentTable=
                   5452: 	&Apache::loncommon::start_data_table().
                   5453: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5454: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5455: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5456: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5457: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5458: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5459: 
                   5460:     $iterator->next(); # skip the first BEGIN_MAP
                   5461:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5462:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5463:     while ($depth > 0) {
1.71      ng       5464:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5465:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5466: 
1.385     albertel 5467:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5468: 	    my $parts = $curRes->parts();
1.71      ng       5469:             my $title = $curRes->compTitle();
                   5470: 	    my $symbx = $curRes->symb();
1.484     albertel 5471: 	    $studentTable.=
                   5472: 		&Apache::loncommon::start_data_table_row().
                   5473: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5474: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5475:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5476: 		.')').'</td>';
1.71      ng       5477: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5478: 
                   5479: 	    my %newrecord=();
                   5480: 	    my @displayPts=();
1.269     raeburn  5481:             my %aggregate = ();
                   5482:             my $aggregateflag = 0;
1.726     raeburn  5483:             if ($env{'form.HIDE'.$prob}) {
                   5484:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5485:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5486:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5487:                 $hideflag += $numchgs;
                   5488:             }
1.71      ng       5489: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5490: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5491: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5492: 
1.257     albertel 5493: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5494: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5495: 		my $partial = $newpts/$wgt;
                   5496: 		my $score;
                   5497: 		if ($partial > 0) {
                   5498: 		    $score = 'correct_by_override';
1.125     ng       5499: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5500: 		    $score = 'incorrect_by_override';
                   5501: 		}
1.257     albertel 5502: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5503: 		if ($dropMenu eq 'excused') {
1.71      ng       5504: 		    $partial = '';
                   5505: 		    $score = 'excused';
1.125     ng       5506: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5507: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5508: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5509: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5510: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5511: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5512: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5513: 		    $changeflag++;
                   5514: 		    $newpts = '';
1.269     raeburn  5515:                     
                   5516:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5517:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5518:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5519:                     if ($aggtries > 0) {
                   5520:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5521:                         $aggregateflag = 1;
                   5522:                     }
1.71      ng       5523: 		}
1.324     albertel 5524: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5525: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5526: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5527: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5528: 		    '&nbsp;<br />';
1.526     raeburn  5529: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5530: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5531: 		    '&nbsp;<br />';
1.71      ng       5532: 		$question++;
1.380     albertel 5533: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5534: 
1.71      ng       5535: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5536: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5537: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5538: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5539: 
                   5540: 		$changeflag++;
                   5541: 	    }
                   5542: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5543: 		my %record = 
                   5544: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5545: 					     $udom,$uname);
                   5546: 
                   5547: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5548: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5549: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5550: 		    $newrecord{'resource.CODE'} = '';
                   5551: 		}
1.257     albertel 5552: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5553: 					$udom,$uname);
1.382     albertel 5554: 		%record = &Apache::lonnet::restore($symbx,
                   5555: 						   $env{'request.course.id'},
                   5556: 						   $udom,$uname);
1.380     albertel 5557: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5558: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5559: 	    }
1.380     albertel 5560: 	    
1.269     raeburn  5561:             if ($aggregateflag) {
                   5562:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5563:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5564:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5565:             }
1.125     ng       5566: 
1.71      ng       5567: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5568: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5569: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5570: 
1.196     albertel 5571: 	    $prob++;
1.68      ng       5572: 	}
1.71      ng       5573:         $curRes = $iterator->next();
1.68      ng       5574:     }
1.98      albertel 5575: 
1.484     albertel 5576:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5577:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5578: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5579: 		  $changeflag).'<br />');
                   5580:     my $hidemsg=($hideflag == 0 ? '' :
                   5581:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5582:                      $hideflag).'<br />');
                   5583:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5584: 
1.70      ng       5585:     return '';
                   5586: }
                   5587: 
1.72      ng       5588: #-------- end of section for handling grading by page/sequence ---------
                   5589: #
                   5590: #-------------------------------------------------------------------
                   5591: 
1.581     www      5592: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5593: #
                   5594: #------ start of section for handling grading by page/sequence ---------
                   5595: 
1.423     albertel 5596: =pod
                   5597: 
                   5598: =head1 Bubble sheet grading routines
                   5599: 
1.424     albertel 5600:   For this documentation:
                   5601: 
                   5602:    'scanline' refers to the full line of characters
                   5603:    from the file that we are parsing that represents one entire sheet
                   5604: 
                   5605:    'bubble line' refers to the data
1.659     raeburn  5606:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5607: 
                   5608: 
1.659     raeburn  5609: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5610: into a course. When a user wants to grade, they select a
1.659     raeburn  5611: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5612: one of the predefined configurations for what each scanline looks
                   5613: like.
                   5614: 
                   5615: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5616: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5617: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5618: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5619: invalid student/employee ID
1.424     albertel 5620: 
                   5621: If the CODE option is used that determines the randomization of the
1.556     weissno  5622: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5623: username:domain.
                   5624: 
                   5625: During the validation phase the instructor can choose to skip scanlines. 
                   5626: 
1.659     raeburn  5627: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5628: 
                   5629:   scantron_original_filename (unmodified original file)
                   5630:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5631:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5632: 
                   5633: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5634: correction information that isn't representable in the bubblesheet
1.424     albertel 5635: file (see &scantron_getfile() for more information)
                   5636: 
                   5637: After all scanlines are either valid, marked as valid or skipped, then
                   5638: foreach line foreach problem in the picked sequence, an ssi request is
                   5639: made that simulates a user submitting their selected letter(s) against
                   5640: the homework problem.
1.423     albertel 5641: 
                   5642: =over 4
                   5643: 
                   5644: 
                   5645: 
                   5646: =item defaultFormData
                   5647: 
                   5648:   Returns html hidden inputs used to hold context/default values.
                   5649: 
                   5650:  Arguments:
                   5651:   $symb - $symb of the current resource 
                   5652: 
                   5653: =cut
1.422     foxr     5654: 
1.81      albertel 5655: sub defaultFormData {
1.324     albertel 5656:     my ($symb)=@_;
1.766     raeburn  5657:     return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5658: }
                   5659: 
1.447     foxr     5660: 
1.423     albertel 5661: =pod 
                   5662: 
                   5663: =item getSequenceDropDown
                   5664: 
                   5665:    Return html dropdown of possible sequences to grade
                   5666:  
                   5667:  Arguments:
1.582     raeburn  5668:    $symb - $symb of the current resource
                   5669:    $map_error - ref to scalar which will container error if
                   5670:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5671: 
                   5672: =cut
1.422     foxr     5673: 
1.75      albertel 5674: sub getSequenceDropDown {
1.582     raeburn  5675:     my ($symb,$map_error)=@_;
1.75      albertel 5676:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5677:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5678:     if (ref($map_error)) {
                   5679:         return if ($$map_error);
                   5680:     }
1.137     albertel 5681:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5682:     my $ctr=0;
                   5683:     foreach (@$titles) {
                   5684: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5685: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5686: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5687: 	    '>'.$showtitle.'</option>'."\n";
                   5688: 	$ctr++;
                   5689:     }
                   5690:     $result.= '</select>';
                   5691:     return $result;
                   5692: }
                   5693: 
1.495     albertel 5694: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5695:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5696: 
                   5697: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5698: 
1.509     raeburn  5699: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5700:                                    # matchresponse or rankresponse, where 
                   5701:                                    # an individual response can have multiple 
                   5702:                                    # lines
1.503     raeburn  5703: 
                   5704: my %responsetype_per_response;     # responsetype for each response
                   5705: 
1.691     raeburn  5706: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5707:                                    # numbered response. Needed when randomorder
                   5708:                                    # or randompick are in use. Key is ID, value 
                   5709:                                    # is response number.
                   5710: 
1.495     albertel 5711: # Save and restore the bubble lines array to the form env.
                   5712: 
                   5713: 
                   5714: sub save_bubble_lines {
                   5715:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5716: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5717: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5718: 	    $first_bubble_line{$line};
1.503     raeburn  5719:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5720:             $subdivided_bubble_lines{$line};
                   5721:         $env{"form.scantron.responsetype.$line"} =
                   5722:             $responsetype_per_response{$line};
1.495     albertel 5723:     }
1.691     raeburn  5724:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5725:         my $line = $masterseq_id_responsenum{$resid};
                   5726:         $env{"form.scantron.residpart.$line"} = $resid;
                   5727:     }
1.495     albertel 5728: }
                   5729: 
                   5730: 
                   5731: sub restore_bubble_lines {
                   5732:     my $line = 0;
                   5733:     %bubble_lines_per_response = ();
1.691     raeburn  5734:     %masterseq_id_responsenum = ();
1.495     albertel 5735:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5736: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5737: 	$bubble_lines_per_response{$line} = $value;
                   5738: 	$first_bubble_line{$line}  =
                   5739: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5740:         $subdivided_bubble_lines{$line} =
                   5741:             $env{"form.scantron.sub_bubblelines.$line"};
                   5742:         $responsetype_per_response{$line} =
                   5743:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5744:         my $id = $env{"form.scantron.residpart.$line"};
                   5745:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5746: 	$line++;
                   5747:     }
                   5748: }
                   5749: 
1.423     albertel 5750: =pod 
                   5751: 
                   5752: =item scantron_filenames
                   5753: 
                   5754:    Returns a list of the scantron files in the current course 
                   5755: 
                   5756: =cut
1.422     foxr     5757: 
1.202     albertel 5758: sub scantron_filenames {
1.257     albertel 5759:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5760:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5761:     my $getpropath = 1;
1.662     raeburn  5762:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5763:                                                         $cname,$getpropath);
1.202     albertel 5764:     my @possiblenames;
1.662     raeburn  5765:     if (ref($dirlist) eq 'ARRAY') {
                   5766:         foreach my $filename (sort(@{$dirlist})) {
                   5767: 	    ($filename)=split(/&/,$filename);
                   5768: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5769: 	    $filename=~s/^scantron_orig_//;
                   5770: 	    push(@possiblenames,$filename);
                   5771:         }
1.202     albertel 5772:     }
                   5773:     return @possiblenames;
                   5774: }
                   5775: 
1.423     albertel 5776: =pod 
                   5777: 
                   5778: =item scantron_uploads
                   5779: 
                   5780:    Returns  html drop-down list of scantron files in current course.
                   5781: 
                   5782:  Arguments:
                   5783:    $file2grade - filename to set as selected in the dropdown
                   5784: 
                   5785: =cut
1.422     foxr     5786: 
1.202     albertel 5787: sub scantron_uploads {
1.209     ng       5788:     my ($file2grade) = @_;
1.202     albertel 5789:     my $result=	'<select name="scantron_selectfile">';
                   5790:     $result.="<option></option>";
                   5791:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5792: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5793:     }
                   5794:     $result.="</select>";
                   5795:     return $result;
                   5796: }
                   5797: 
1.423     albertel 5798: =pod 
                   5799: 
                   5800: =item scantron_scantab
                   5801: 
                   5802:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5803:   file.
                   5804: 
                   5805: =cut
1.422     foxr     5806: 
1.82      albertel 5807: sub scantron_scantab {
                   5808:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5809:     $result.='<option></option>'."\n";
1.754     raeburn  5810:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5811:     if (@lines > 0) {
                   5812:         foreach my $line (@lines) {
                   5813:             next if (($line =~ /^\#/) || ($line eq ''));
                   5814: 	    my ($name,$descrip)=split(/:/,$line);
                   5815: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5816:         }
1.82      albertel 5817:     }
                   5818:     $result.='</select>'."\n";
1.518     raeburn  5819:     return $result;
                   5820: }
                   5821: 
1.423     albertel 5822: =pod 
                   5823: 
                   5824: =item scantron_CODElist
                   5825: 
                   5826:   Returns html drop down of the saved CODE lists from current course,
                   5827:   generated from earlier printings.
                   5828: 
                   5829: =cut
1.422     foxr     5830: 
1.186     albertel 5831: sub scantron_CODElist {
1.257     albertel 5832:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5833:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5834:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5835:     my $namechoice='<option></option>';
1.225     albertel 5836:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5837: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5838: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5839: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5840:     }
                   5841:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5842:     return $namechoice;
                   5843: }
                   5844: 
1.423     albertel 5845: =pod 
                   5846: 
                   5847: =item scantron_CODEunique
                   5848: 
                   5849:   Returns the html for "Each CODE to be used once" radio.
                   5850: 
                   5851: =cut
1.422     foxr     5852: 
1.186     albertel 5853: sub scantron_CODEunique {
1.532     bisitz   5854:     my $result='<span class="LC_nobreak">
1.272     albertel 5855:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5856:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5857:                 </span>
1.532     bisitz   5858:                 <span class="LC_nobreak">
1.272     albertel 5859:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5860:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5861:                 </span>';
1.186     albertel 5862:     return $result;
                   5863: }
1.423     albertel 5864: 
                   5865: =pod 
                   5866: 
                   5867: =item scantron_selectphase
                   5868: 
1.659     raeburn  5869:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5870:   Allows for - starting a grading run.
1.424     albertel 5871:              - downloading existing scan data (original, corrected
1.423     albertel 5872:                                                 or skipped info)
                   5873: 
                   5874:              - uploading new scan data
                   5875: 
                   5876:  Arguments:
                   5877:   $r          - The Apache request object
                   5878:   $file2grade - name of the file that contain the scanned data to score
                   5879: 
                   5880: =cut
1.186     albertel 5881: 
1.75      albertel 5882: sub scantron_selectphase {
1.608     www      5883:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5884:     if (!$symb) {return '';}
1.582     raeburn  5885:     my $map_error;
                   5886:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5887:     if ($map_error) {
                   5888:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5889:         return;
                   5890:     }
1.324     albertel 5891:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5892:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5893:     my $format_selector=&scantron_scantab();
1.186     albertel 5894:     my $CODE_selector=&scantron_CODElist();
                   5895:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5896:     my $result;
1.422     foxr     5897: 
1.513     foxr     5898:     $ssi_error = 0;
                   5899: 
1.770     raeburn  5900:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'}) {
1.606     wenzelju 5901: 
                   5902: 	# Chunk of form to prompt for a scantron file upload.
                   5903: 
                   5904:         $r->print('
1.754     raeburn  5905:     <br />');
1.606     wenzelju 5906:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5907:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.770     raeburn  5908:     my $csec= $env{'request.course.sec'};
1.736     damieng  5909:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5910:     &js_escape(\$alertmsg);
1.754     raeburn  5911:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 5912:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5913:     function checkUpload(formname) {
                   5914: 	if (formname.upfile.value == "") {
1.736     damieng  5915: 	    alert("'.$alertmsg.'");
1.606     wenzelju 5916: 	    return false;
                   5917: 	}
                   5918: 	formname.submit();
1.756     raeburn  5919:     }'."\n".$formatjs));
1.606     wenzelju 5920:     $r->print('
                   5921:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5922:                 '.$default_form_data.'
                   5923:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
1.770     raeburn  5924:                 <input name="coursesec" type="hidden" value="'.$csec.'" />
1.606     wenzelju 5925:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5926:                 <input name="command" value="scantronupload_save" type="hidden" />
1.754     raeburn  5927:               '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5928:               '.&Apache::loncommon::start_data_table_header_row().'
                   5929:                 <th>
                   5930:                 &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5931:                 </th>
                   5932:               '.&Apache::loncommon::end_data_table_header_row().'
                   5933:               '.&Apache::loncommon::start_data_table_row().'
                   5934:             <td>
                   5935:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
                   5936:     if ($formatoptions) {
                   5937:         $r->print('</td>
                   5938:                  '.&Apache::loncommon::end_data_table_row().'
                   5939:                  '.&Apache::loncommon::start_data_table_row().'
                   5940:                  <td>'.$formattitle.('&nbsp;'x2).$formatoptions.'
                   5941:                  </td>
                   5942:                  '.&Apache::loncommon::end_data_table_row().'
                   5943:                  '.&Apache::loncommon::start_data_table_row().'
                   5944:                  <td>'
                   5945:         );
                   5946:     } else {
                   5947:         $r->print(' <br />');
                   5948:     }
                   5949:     $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5950:               </td>
                   5951:              '.&Apache::loncommon::end_data_table_row().'
                   5952:              '.&Apache::loncommon::end_data_table().'
                   5953:              </form>'
                   5954:     );
1.606     wenzelju 5955: 
                   5956:     }
                   5957: 
1.422     foxr     5958:     # Chunk of form to prompt for a file to grade and how:
                   5959: 
1.489     albertel 5960:     $result.= '
                   5961:     <br />
                   5962:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5963:     <input type="hidden" name="command" value="scantron_warning" />
                   5964:     '.$default_form_data.'
                   5965:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5966:        '.&Apache::loncommon::start_data_table_header_row().'
                   5967:             <th colspan="2">
1.492     albertel 5968:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5969:             </th>
                   5970:        '.&Apache::loncommon::end_data_table_header_row().'
                   5971:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5972:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5973:        '.&Apache::loncommon::end_data_table_row().'
                   5974:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5975:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_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('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5979:        '.&Apache::loncommon::end_data_table_row().'
                   5980:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5981:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_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('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5985:        '.&Apache::loncommon::end_data_table_row().'
                   5986:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5987: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5988:             <td>
1.492     albertel 5989: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5990:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5991:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5992: 	    </td>
1.489     albertel 5993:        '.&Apache::loncommon::end_data_table_row().'
                   5994:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5995:             <td colspan="2">
1.572     www      5996:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5997:             </td>
1.489     albertel 5998:        '.&Apache::loncommon::end_data_table_row().'
                   5999:     '.&Apache::loncommon::end_data_table().'
                   6000:     </form>
                   6001: ';
1.162     albertel 6002:    
                   6003:     $r->print($result);
                   6004: 
1.422     foxr     6005:     # Chunk of the form that prompts to view a scoring office file,
                   6006:     # corrected file, skipped records in a file.
                   6007: 
1.489     albertel 6008:     $r->print('
                   6009:    <br />
                   6010:    <form action="/adm/grades" name="scantron_download">
                   6011:      '.$default_form_data.'
                   6012:      <input type="hidden" name="command" value="scantron_download" />
                   6013:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6014:        '.&Apache::loncommon::start_data_table_header_row().'
                   6015:               <th>
1.492     albertel 6016:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6017:               </th>
                   6018:        '.&Apache::loncommon::end_data_table_header_row().'
                   6019:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6020:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6021:                 <br />
1.492     albertel 6022:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6023:        '.&Apache::loncommon::end_data_table_row().'
                   6024:      '.&Apache::loncommon::end_data_table().'
                   6025:    </form>
                   6026:    <br />
                   6027: ');
1.162     albertel 6028: 
1.457     banghart 6029:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6030: 
1.694     bisitz   6031:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6032:              $default_form_data."\n".
                   6033:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6034:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6035:              '<th colspan="2">
1.572     www      6036:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6037:              '</th>'."\n".
                   6038:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6039:               &Apache::loncommon::start_data_table_row()."\n".
                   6040:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6041:               '<td> '.$sequence_selector.' </td>'.
                   6042:               &Apache::loncommon::end_data_table_row()."\n".
                   6043:               &Apache::loncommon::start_data_table_row()."\n".
                   6044:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6045:               '<td> '.$file_selector.' </td>'."\n".
                   6046:               &Apache::loncommon::end_data_table_row()."\n".
                   6047:               &Apache::loncommon::start_data_table_row()."\n".
                   6048:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6049:               '<td> '.$format_selector.' </td>'."\n".
                   6050:               &Apache::loncommon::end_data_table_row()."\n".
                   6051:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6052:               '<td> '.&mt('Options').' </td>'."\n".
                   6053:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6054:               &Apache::loncommon::end_data_table_row()."\n".
                   6055:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6056:               '<td colspan="2">'."\n".
                   6057:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6058:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6059:               '</td>'."\n".
                   6060:               &Apache::loncommon::end_data_table_row()."\n".
                   6061:               &Apache::loncommon::end_data_table()."\n".
                   6062:               '</form><br />');
                   6063:     return;
1.75      albertel 6064: }
                   6065: 
1.423     albertel 6066: =pod 
                   6067: 
                   6068: =item username_to_idmap
                   6069: 
1.556     weissno  6070:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6071:     student username:domain. If a single ID occurs for more than one student,
                   6072:     the status of the student is checked, and if Active, the value in the hash
                   6073:     will be set to the Active student.
1.423     albertel 6074: 
                   6075:   Arguments:
                   6076: 
                   6077:     $classlist - reference to the class list hash. This is a hash
                   6078:                  keyed by student name:domain  whose elements are references
1.424     albertel 6079:                  to arrays containing various chunks of information
1.423     albertel 6080:                  about the student. (See loncoursedata for more info).
                   6081: 
                   6082:   Returns
                   6083:     %idmap - the constructed hash
                   6084: 
                   6085: =cut
                   6086: 
1.82      albertel 6087: sub username_to_idmap {
                   6088:     my ($classlist)= @_;
                   6089:     my %idmap;
                   6090:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6091:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6092:         unless ($id eq '') {
                   6093:             if (!exists($idmap{$id})) {
                   6094:                 $idmap{$id} = $student;
                   6095:             } else {
                   6096:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6097:                 if ($status eq 'Active') {
                   6098:                     $idmap{$id} = $student;
                   6099:                 }
                   6100:             }
                   6101:         }
1.82      albertel 6102:     }
                   6103:     return %idmap;
                   6104: }
1.423     albertel 6105: 
                   6106: =pod
                   6107: 
1.424     albertel 6108: =item scantron_fixup_scanline
1.423     albertel 6109: 
                   6110:    Process a requested correction to a scanline.
                   6111: 
                   6112:   Arguments:
1.754     raeburn  6113:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6114:     $scan_data         - hash of correction information 
                   6115:                           (see &scantron_getfile())
                   6116:     $line              - existing scanline
                   6117:     $whichline         - line number of the passed in scanline
                   6118:     $field             - type of change to process 
                   6119:                          (either 
1.573     bisitz   6120:                           'ID'     -> correct the student/employee ID
1.423     albertel 6121:                           'CODE'   -> correct the CODE
                   6122:                           'answer' -> fixup the submitted answers)
                   6123:     
                   6124:    $args               - hash of additional info,
                   6125:                           - 'ID' 
                   6126:                                'newid' -> studentID to use in replacement
1.424     albertel 6127:                                           of existing one
1.423     albertel 6128:                           - 'CODE' 
                   6129:                                'CODE_ignore_dup' - set to true if duplicates
                   6130:                                                    should be ignored.
                   6131: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6132:                                         if the existing unfound code should
1.423     albertel 6133:                                         be used as is
                   6134:                           - 'answer'
                   6135:                                'response' - new answer or 'none' if blank
                   6136:                                'question' - the bubble line to change
1.503     raeburn  6137:                                'questionnum' - the question identifier,
                   6138:                                                may include subquestion. 
1.423     albertel 6139: 
                   6140:   Returns:
                   6141:     $line - the modified scanline
                   6142: 
                   6143:   Side effects: 
                   6144:     $scan_data - may be updated
                   6145: 
                   6146: =cut
                   6147: 
1.82      albertel 6148: 
1.157     albertel 6149: sub scantron_fixup_scanline {
                   6150:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6151:     if ($field eq 'ID') {
                   6152: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6153: 	    return ($line,1,'New value too large');
1.157     albertel 6154: 	}
                   6155: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6156: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6157: 				     $args->{'newid'});
                   6158: 	}
                   6159: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6160: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6161: 	if ($args->{'newid'}=~/^\s*$/) {
                   6162: 	    &scan_data($scan_data,"$whichline.user",
                   6163: 		       $args->{'username'}.':'.$args->{'domain'});
                   6164: 	}
1.186     albertel 6165:     } elsif ($field eq 'CODE') {
1.192     albertel 6166: 	if ($args->{'CODE_ignore_dup'}) {
                   6167: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6168: 	}
                   6169: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6170: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6171: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6172: 		return ($line,1,'New CODE value too large');
                   6173: 	    }
                   6174: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6175: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6176: 	    }
                   6177: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6178: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6179: 	}
1.157     albertel 6180:     } elsif ($field eq 'answer') {
1.497     foxr     6181: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6182: 	my $off=$scantron_config->{'Qoff'};
                   6183: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6184: 	my $answer=${off}x$length;
                   6185: 	if ($args->{'response'} eq 'none') {
                   6186: 	    &scan_data($scan_data,
1.503     raeburn  6187: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6188: 	} else {
                   6189: 	    if ($on eq 'letter') {
                   6190: 		my @alphabet=('A'..'Z');
                   6191: 		$answer=$alphabet[$args->{'response'}];
                   6192: 	    } elsif ($on eq 'number') {
                   6193: 		$answer=$args->{'response'}+1;
                   6194: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6195: 	    } else {
1.497     foxr     6196: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6197: 	    }
1.497     foxr     6198: 	    &scan_data($scan_data,
1.503     raeburn  6199: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6200: 	}
1.497     foxr     6201: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6202: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6203:     }
                   6204:     return $line;
                   6205: }
1.423     albertel 6206: 
                   6207: =pod
                   6208: 
                   6209: =item scan_data
                   6210: 
                   6211:     Edit or look up  an item in the scan_data hash.
                   6212: 
                   6213:   Arguments:
                   6214:     $scan_data  - The hash (see scantron_getfile)
                   6215:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6216:                   scantronfilename_key).
1.423     albertel 6217:     $data        - New value of the hash entry.
                   6218:     $delete      - If true, the entry is removed from the hash.
                   6219: 
                   6220:   Returns:
                   6221:     The new value of the hash table field (undefined if deleted).
                   6222: 
                   6223: =cut
                   6224: 
                   6225: 
1.157     albertel 6226: sub scan_data {
                   6227:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6228:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6229:     if (defined($value)) {
                   6230: 	$scan_data->{$filename.'_'.$key} = $value;
                   6231:     }
                   6232:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6233:     return $scan_data->{$filename.'_'.$key};
                   6234: }
1.423     albertel 6235: 
1.495     albertel 6236: # ----- These first few routines are general use routines.----
                   6237: 
                   6238: # Return the number of occurences of a pattern in a string.
                   6239: 
                   6240: sub occurence_count {
                   6241:     my ($string, $pattern) = @_;
                   6242: 
                   6243:     my @matches = ($string =~ /$pattern/g);
                   6244: 
                   6245:     return scalar(@matches);
                   6246: }
                   6247: 
                   6248: 
                   6249: # Take a string known to have digits and convert all the
                   6250: # digits into letters in the range J,A..I.
                   6251: 
                   6252: sub digits_to_letters {
                   6253:     my ($input) = @_;
                   6254: 
                   6255:     my @alphabet = ('J', 'A'..'I');
                   6256: 
                   6257:     my @input    = split(//, $input);
                   6258:     my $output ='';
                   6259:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6260: 	if ($input[$i] =~ /\d/) {
                   6261: 	    $output .= $alphabet[$input[$i]];
                   6262: 	} else {
                   6263: 	    $output .= $input[$i];
                   6264: 	}
                   6265:     }
                   6266:     return $output;
                   6267: }
                   6268: 
1.423     albertel 6269: =pod 
                   6270: 
                   6271: =item scantron_parse_scanline
                   6272: 
1.711     bisitz   6273:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6274: 
                   6275:  Arguments:
1.711     bisitz   6276:     line             - The text of the bubblesheet file line to process
1.423     albertel 6277:     whichline        - Line number
1.711     bisitz   6278:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6279:     scan_data        - Hash of extra information about the scanline
                   6280:                        (see scantron_getfile for more information)
                   6281:     just_header      - True if should not process question answers but only
                   6282:                        the stuff to the left of the answers.
1.691     raeburn  6283:     randomorder      - True if randomorder in use
                   6284:     randompick       - True if randompick in use
                   6285:     sequence         - Exam folder URL
                   6286:     master_seq       - Ref to array containing symbs in exam folder
                   6287:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6288:                        (corresponding values are resource objects)
                   6289:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6290:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6291:                        are refs to an array of resource objects, ordered
                   6292:                        according to order used for CODE, when randomorder
                   6293:                        and or randompick are in use.
                   6294:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6295:                        for current line to question number used for same question
                   6296:                         in "Master Sequence" (as seen by Course Coordinator).
                   6297:     startline        - Ref to hash where key is question number (0 is first)
                   6298:                        and value is number of first bubble line for current 
                   6299:                        student or code-based randompick and/or randomorder.
                   6300:     totalref         - Ref of scalar used to score total number of bubble
                   6301:                        lines needed for responses in a scan line (used when
                   6302:                        randompick in use. 
                   6303:     
1.423     albertel 6304:  Returns:
                   6305:    Hash containing the result of parsing the scanline
                   6306: 
                   6307:    Keys are all proceeded by the string 'scantron.'
                   6308: 
                   6309:        CODE    - the CODE in use for this scanline
                   6310:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6311:                  by the operator
                   6312:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6313:                             CODEs were selected, but the usage has been
                   6314:                             forced by the operator
1.556     weissno  6315:        ID  - student/employee ID
1.423     albertel 6316:        PaperID - if used, the ID number printed on the sheet when the 
                   6317:                  paper was scanned
                   6318:        FirstName - first name from the sheet
                   6319:        LastName  - last name from the sheet
                   6320: 
                   6321:      if just_header was not true these key may also exist
                   6322: 
1.447     foxr     6323:        missingerror - a list of bubble ranges that are considered to be answers
                   6324:                       to a single question that don't have any bubbles filled in.
                   6325:                       Of the form questionnumber:firstbubblenumber:count.
                   6326:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6327:                       to a single question that have more than one bubble filled in.
                   6328:                       Of the form questionnumber::firstbubblenumber:count
                   6329:    
                   6330:                 In the above, count is the number of bubble responses in the
                   6331:                 input line needed to represent the possible answers to the question.
                   6332:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6333:                 per line would have count = 2.
                   6334: 
1.423     albertel 6335:        maxquest     - the number of the last bubble line that was parsed
                   6336: 
                   6337:        (<number> starts at 1)
                   6338:        <number>.answer - zero or more letters representing the selected
                   6339:                          letters from the scanline for the bubble line 
                   6340:                          <number>.
                   6341:                          if blank there was either no bubble or there where
                   6342:                          multiple bubbles, (consult the keys missingerror and
                   6343:                          doubleerror if this is an error condition)
                   6344: 
                   6345: =cut
                   6346: 
1.82      albertel 6347: sub scantron_parse_scanline {
1.691     raeburn  6348:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6349:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6350:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6351: 
1.82      albertel 6352:     my %record;
1.691     raeburn  6353:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6354:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6355: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6356: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6357: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6358: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6359: 	    $record{'scantron.CODE'}=substr($data,
                   6360: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6361: 					    $$scantron_config{'CODElength'});
1.191     albertel 6362: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6363: 		$record{'scantron.useCODE'}=1;
                   6364: 	    }
1.192     albertel 6365: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6366: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6367: 	    }
1.82      albertel 6368: 	} else {
                   6369: 	    #FIXME interpret first N questions
                   6370: 	}
                   6371:     }
1.83      albertel 6372:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6373: 				  $$scantron_config{'IDlength'});
1.157     albertel 6374:     $record{'scantron.PaperID'}=
                   6375: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6376: 	       $$scantron_config{'PaperIDlength'});
                   6377:     $record{'scantron.FirstName'}=
                   6378: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6379: 	       $$scantron_config{'FirstNamelength'});
                   6380:     $record{'scantron.LastName'}=
                   6381: 	substr($data,$$scantron_config{'LastName'}-1,
                   6382: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6383:     if ($just_header) { return \%record; }
1.194     albertel 6384: 
1.82      albertel 6385:     my @alphabet=('A'..'Z');
                   6386:     my $questnum=0;
1.447     foxr     6387:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6388: 
1.691     raeburn  6389:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6390:     if ($randompick || $randomorder) {
                   6391:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6392:                                          $master_seq,$symb_to_resource,
                   6393:                                          $partids_by_symb,$orderedforcode,
                   6394:                                          $respnumlookup,$startline);
                   6395:         if ($total) {
                   6396:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6397:         }
                   6398:         if (ref($totalref)) {
                   6399:             $$totalref = $total;
                   6400:         }
                   6401:     }
                   6402:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6403:     chomp($questions);		# Get rid of any trailing \n.
                   6404:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6405:     while (length($questions)) {
1.691     raeburn  6406:         my $answers_needed;
                   6407:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6408:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6409:         } else {
                   6410: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6411:         }
1.503     raeburn  6412:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6413:                              || 1;
                   6414:         $questnum++;
                   6415:         my $quest_id = $questnum;
                   6416:         my $currentquest = substr($questions,0,$answer_length);
                   6417:         $questions       = substr($questions,$answer_length);
                   6418:         if (length($currentquest) < $answer_length) { next; }
                   6419: 
1.691     raeburn  6420:         my $subdivided;
                   6421:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6422:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6423:         } else {
                   6424:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6425:         }
                   6426:         if ($subdivided =~ /,/) {
1.503     raeburn  6427:             my $subquestnum = 1;
                   6428:             my $subquestions = $currentquest;
1.691     raeburn  6429:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6430:             foreach my $subans (@subanswers_needed) {
                   6431:                 my $subans_length =
                   6432:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6433:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6434:                 $subquestions   = substr($subquestions,$subans_length);
                   6435:                 $quest_id = "$questnum.$subquestnum";
                   6436:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6437:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6438:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6439:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6440:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6441:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6442:                 } else {
                   6443:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6444:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6445:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6446:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6447:                 }
                   6448:                 $subquestnum ++;
                   6449:             }
                   6450:         } else {
                   6451:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6452:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6453:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6454:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6455:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6456:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6457:             } else {
                   6458:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6459:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6460:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6461:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6462:             }
                   6463:         }
                   6464:     }
                   6465:     $record{'scantron.maxquest'}=$questnum;
                   6466:     return \%record;
                   6467: }
1.447     foxr     6468: 
1.691     raeburn  6469: sub get_master_seq {
                   6470:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6471:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6472:                    (ref($symb_to_resource) eq 'HASH'));
                   6473:     my $resource_error;
                   6474:     foreach my $resource (@{$resources}) {
                   6475:         my $ressymb;
                   6476:         if (ref($resource)) {
                   6477:             $ressymb = $resource->symb();
                   6478:             push(@{$master_seq},$ressymb);
                   6479:             $symb_to_resource->{$ressymb} = $resource;
                   6480:         } else {
                   6481:             $resource_error = 1;
                   6482:             last;
                   6483:         }
                   6484:     }
                   6485:     return $resource_error;
                   6486: }
                   6487: 
                   6488: sub get_respnum_lookups {
                   6489:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6490:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6491:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6492:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6493:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6494:                    (ref($startline) eq 'HASH'));
                   6495:     my ($user,$scancode);
                   6496:     if ((exists($record->{'scantron.CODE'})) &&
                   6497:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6498:         $scancode = $record->{'scantron.CODE'};
                   6499:     } else {
                   6500:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6501:     }
                   6502:     my @mapresources =
                   6503:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6504:                      $orderedforcode);
                   6505:     my $total = 0;
                   6506:     my $count = 0;
                   6507:     foreach my $resource (@mapresources) {
                   6508:         my $id = $resource->id();
                   6509:         my $symb = $resource->symb();
                   6510:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6511:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6512:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6513:                 if ($respnum ne '') {
                   6514:                     $respnumlookup->{$count} = $respnum;
                   6515:                     $startline->{$count} = $total;
                   6516:                     $total += $bubble_lines_per_response{$respnum};
                   6517:                     $count ++;
                   6518:                 }
                   6519:             }
                   6520:         }
                   6521:     }
                   6522:     return $total;
                   6523: }
                   6524: 
1.503     raeburn  6525: sub scantron_validator_lettnum {
                   6526:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6527:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6528:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6529: 
                   6530:     # Qon 'letter' implies for each slot in currquest we have:
                   6531:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6532:     #    about anything else (esp. a value of Qoff) for missing
                   6533:     #    bubbles.
                   6534:     #
                   6535:     # Qon 'number' implies each slot gives a digit that indexes the
                   6536:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6537:     #    and * or ? for double bubbles on a single line.
                   6538:     #
1.447     foxr     6539: 
1.503     raeburn  6540:     my $matchon;
                   6541:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6542:         $matchon = '[A-Z]';
                   6543:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6544:         $matchon = '\d';
                   6545:     }
                   6546:     my $occurrences = 0;
1.691     raeburn  6547:     my $responsenum = $questnum-1;
                   6548:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6549:        $responsenum = $respnumlookup->{$questnum-1} 
                   6550:     }
                   6551:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6552:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6553:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6554:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6555:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6556:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6557:         my @singlelines = split('',$currquest);
                   6558:         foreach my $entry (@singlelines) {
                   6559:             $occurrences = &occurence_count($entry,$matchon);
                   6560:             if ($occurrences > 1) {
                   6561:                 last;
                   6562:             }
1.691     raeburn  6563:         }
1.503     raeburn  6564:     } else {
                   6565:         $occurrences = &occurence_count($currquest,$matchon); 
                   6566:     }
                   6567:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6568:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6569:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6570:             my $bubble = substr($currquest,$ans,1);
                   6571:             if ($bubble =~ /$matchon/ ) {
                   6572:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6573:                     if ($bubble == 0) {
                   6574:                         $bubble = 10; 
                   6575:                     }
                   6576:                     $record->{"scantron.$ansnum.answer"} = 
                   6577:                         $alphabet->[$bubble-1];
                   6578:                 } else {
                   6579:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6580:                 }
                   6581:             } else {
                   6582:                 $record->{"scantron.$ansnum.answer"}='';
                   6583:             }
                   6584:             $ansnum++;
                   6585:         }
                   6586:     } elsif (!defined($currquest)
                   6587:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6588:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6589:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6590:             $record->{"scantron.$ansnum.answer"}='';
                   6591:             $ansnum++;
                   6592:         }
                   6593:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6594:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6595:         }
                   6596:     } else {
                   6597:         if ($$scantron_config{'Qon'} eq 'number') {
                   6598:             $currquest = &digits_to_letters($currquest);            
                   6599:         }
                   6600:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6601:             my $bubble = substr($currquest,$ans,1);
                   6602:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6603:             $ansnum++;
                   6604:         }
                   6605:     }
                   6606:     return $ansnum;
                   6607: }
1.447     foxr     6608: 
1.503     raeburn  6609: sub scantron_validator_positional {
                   6610:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6611:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6612:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6613: 
1.503     raeburn  6614:     # Otherwise there's a positional notation;
                   6615:     # each bubble line requires Qlength items, and there are filled in
                   6616:     # bubbles for each case where there 'Qon' characters.
                   6617:     #
1.447     foxr     6618: 
1.503     raeburn  6619:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6620: 
1.503     raeburn  6621:     # If the split only gives us one element.. the full length of the
                   6622:     # answer string, no bubbles are filled in:
1.447     foxr     6623: 
1.507     raeburn  6624:     if ($answers_needed eq '') {
                   6625:         return;
                   6626:     }
                   6627: 
1.503     raeburn  6628:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6629:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6630:             $record->{"scantron.$ansnum.answer"}='';
                   6631:             $ansnum++;
                   6632:         }
                   6633:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6634:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6635:         }
                   6636:     } elsif (scalar(@array) == 2) {
                   6637:         my $location = length($array[0]);
                   6638:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6639:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6640:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6641:             if ($ans eq $line_num) {
                   6642:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6643:             } else {
                   6644:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6645:             }
                   6646:             $ansnum++;
                   6647:          }
                   6648:     } else {
                   6649:         #  If there's more than one instance of a bubble character
                   6650:         #  That's a double bubble; with positional notation we can
                   6651:         #  record all the bubbles filled in as well as the
                   6652:         #  fact this response consists of multiple bubbles.
                   6653:         #
1.691     raeburn  6654:         my $responsenum = $questnum-1;
                   6655:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6656:             $responsenum = $respnumlookup->{$questnum-1}
                   6657:         }
                   6658:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6659:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6660:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6661:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6662:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6663:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6664:             my $doubleerror = 0;
                   6665:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6666:                    (!$doubleerror)) {
                   6667:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6668:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6669:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6670:                if (length(@currarray) > 2) {
                   6671:                    $doubleerror = 1;
                   6672:                } 
                   6673:             }
                   6674:             if ($doubleerror) {
                   6675:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6676:             }
                   6677:         } else {
                   6678:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6679:         }
                   6680:         my $item = $ansnum;
                   6681:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6682:             $record->{"scantron.$item.answer"} = '';
                   6683:             $item ++;
                   6684:         }
1.447     foxr     6685: 
1.503     raeburn  6686:         my @ans=@array;
                   6687:         my $i=0;
                   6688:         my $increment = 0;
                   6689:         while ($#ans) {
                   6690:             $i+=length($ans[0]) + $increment;
                   6691:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6692:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6693:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6694:             shift(@ans);
                   6695:             $increment = 1;
                   6696:         }
                   6697:         $ansnum += $answers_needed;
1.82      albertel 6698:     }
1.503     raeburn  6699:     return $ansnum;
1.82      albertel 6700: }
                   6701: 
1.423     albertel 6702: =pod
                   6703: 
                   6704: =item scantron_add_delay
                   6705: 
                   6706:    Adds an error message that occurred during the grading phase to a
                   6707:    queue of messages to be shown after grading pass is complete
                   6708: 
                   6709:  Arguments:
1.424     albertel 6710:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6711:    $scanline    - the scanline that caused the error
                   6712:    $errormesage - the error message
                   6713:    $errorcode   - a numeric code for the error
                   6714: 
                   6715:  Side Effects:
1.424     albertel 6716:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6717: 
                   6718: =cut
                   6719: 
1.82      albertel 6720: sub scantron_add_delay {
1.140     albertel 6721:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6722:     push(@$delayqueue,
                   6723: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6724: 	  'ecode' => $errorcode }
                   6725: 	 );
1.82      albertel 6726: }
                   6727: 
1.423     albertel 6728: =pod
                   6729: 
                   6730: =item scantron_find_student
                   6731: 
1.424     albertel 6732:    Finds the username for the current scanline
                   6733: 
                   6734:   Arguments:
                   6735:    $scantron_record - hash result from scantron_parse_scanline
                   6736:    $scan_data       - hash of correction information 
                   6737:                       (see &scantron_getfile() form more information)
                   6738:    $idmap           - hash from &username_to_idmap()
                   6739:    $line            - number of current scanline
                   6740:  
                   6741:   Returns:
                   6742:    Either 'username:domain' or undef if unknown
                   6743: 
1.423     albertel 6744: =cut
                   6745: 
1.82      albertel 6746: sub scantron_find_student {
1.157     albertel 6747:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6748:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6749:     if ($scanID =~ /^\s*$/) {
                   6750:  	return &scan_data($scan_data,"$line.user");
                   6751:     }
1.83      albertel 6752:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6753:  	if (lc($id) eq lc($scanID)) {
                   6754:  	    return $$idmap{$id};
                   6755:  	}
1.83      albertel 6756:     }
                   6757:     return undef;
                   6758: }
                   6759: 
1.423     albertel 6760: =pod
                   6761: 
                   6762: =item scantron_filter
                   6763: 
1.424     albertel 6764:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6765:    hidden resources was selected
                   6766: 
1.423     albertel 6767: =cut
                   6768: 
1.83      albertel 6769: sub scantron_filter {
                   6770:     my ($curres)=@_;
1.331     albertel 6771: 
                   6772:     if (ref($curres) && $curres->is_problem()) {
                   6773: 	# if the user has asked to not have either hidden
                   6774: 	# or 'randomout' controlled resources to be graded
                   6775: 	# don't include them
                   6776: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6777: 	    && $curres->randomout) {
                   6778: 	    return 0;
                   6779: 	}
1.83      albertel 6780: 	return 1;
                   6781:     }
                   6782:     return 0;
1.82      albertel 6783: }
                   6784: 
1.423     albertel 6785: =pod
                   6786: 
                   6787: =item scantron_process_corrections
                   6788: 
1.424     albertel 6789:    Gets correction information out of submitted form data and corrects
                   6790:    the scanline
                   6791: 
1.423     albertel 6792: =cut
                   6793: 
1.157     albertel 6794: sub scantron_process_corrections {
                   6795:     my ($r) = @_;
1.754     raeburn  6796:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6797:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6798:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6799:     my $which=$env{'form.scantron_line'};
1.200     albertel 6800:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6801:     my ($skip,$err,$errmsg);
1.257     albertel 6802:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6803: 	$skip=1;
1.257     albertel 6804:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6805: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6806: 	    $env{'form.scantron_domain'};
1.157     albertel 6807: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6808: 	($line,$err,$errmsg)=
                   6809: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6810: 				     'ID',{'newid'=>$newid,
1.257     albertel 6811: 				    'username'=>$env{'form.scantron_username'},
                   6812: 				    'domain'=>$env{'form.scantron_domain'}});
                   6813:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6814: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6815: 	my $newCODE;
1.192     albertel 6816: 	my %args;
1.190     albertel 6817: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6818: 	    $newCODE='use_unfound';
1.190     albertel 6819: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6820: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6821: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6822: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6823: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6824: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6825: 	}
1.257     albertel 6826: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6827: 	    $args{'CODE_ignore_dup'}=1;
                   6828: 	}
                   6829: 	$args{'CODE'}=$newCODE;
1.186     albertel 6830: 	($line,$err,$errmsg)=
                   6831: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6832: 				     'CODE',\%args);
1.257     albertel 6833:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6834: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6835: 	    ($line,$err,$errmsg)=
                   6836: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6837: 					 $which,'answer',
                   6838: 					 { 'question'=>$question,
1.503     raeburn  6839: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6840:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6841: 	    if ($err) { last; }
                   6842: 	}
                   6843:     }
                   6844:     if ($err) {
1.703     bisitz   6845:         $r->print(
                   6846:             '<p class="LC_error">'
                   6847:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6848:                 $errmsg)
1.704     raeburn  6849:            .'</p>');
1.157     albertel 6850:     } else {
1.200     albertel 6851: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6852: 	&scantron_putfile($scanlines,$scan_data);
                   6853:     }
                   6854: }
                   6855: 
1.423     albertel 6856: =pod
                   6857: 
                   6858: =item reset_skipping_status
                   6859: 
1.424     albertel 6860:    Forgets the current set of remember skipped scanlines (and thus
                   6861:    reverts back to considering all lines in the
                   6862:    scantron_skipped_<filename> file)
                   6863: 
1.423     albertel 6864: =cut
                   6865: 
1.200     albertel 6866: sub reset_skipping_status {
                   6867:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6868:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6869:     &scantron_putfile(undef,$scan_data);
                   6870: }
                   6871: 
1.423     albertel 6872: =pod
                   6873: 
                   6874: =item start_skipping
                   6875: 
1.424     albertel 6876:    Marks a scanline to be skipped. 
                   6877: 
1.423     albertel 6878: =cut
                   6879: 
1.376     albertel 6880: sub start_skipping {
1.200     albertel 6881:     my ($scan_data,$i)=@_;
                   6882:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6883:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6884: 	$remembered{$i}=2;
                   6885:     } else {
                   6886: 	$remembered{$i}=1;
                   6887:     }
1.200     albertel 6888:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6889: }
                   6890: 
1.423     albertel 6891: =pod
                   6892: 
                   6893: =item should_be_skipped
                   6894: 
1.424     albertel 6895:    Checks whether a scanline should be skipped.
                   6896: 
1.423     albertel 6897: =cut
                   6898: 
1.200     albertel 6899: sub should_be_skipped {
1.376     albertel 6900:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6901:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6902: 	# not redoing old skips
1.376     albertel 6903: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6904: 	return 0;
                   6905:     }
                   6906:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6907: 
                   6908:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6909: 	return 0;
                   6910:     }
1.200     albertel 6911:     return 1;
                   6912: }
                   6913: 
1.423     albertel 6914: =pod
                   6915: 
                   6916: =item remember_current_skipped
                   6917: 
1.424     albertel 6918:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6919:    file and remembers them into scan_data for later use.
                   6920: 
1.423     albertel 6921: =cut
                   6922: 
1.200     albertel 6923: sub remember_current_skipped {
                   6924:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6925:     my %to_remember;
                   6926:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6927: 	if ($scanlines->{'skipped'}[$i]) {
                   6928: 	    $to_remember{$i}=1;
                   6929: 	}
                   6930:     }
1.376     albertel 6931: 
1.200     albertel 6932:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6933:     &scantron_putfile(undef,$scan_data);
                   6934: }
                   6935: 
1.423     albertel 6936: =pod
                   6937: 
                   6938: =item check_for_error
                   6939: 
1.424     albertel 6940:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6941:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6942:     something went wrong.
                   6943: 
1.423     albertel 6944: =cut
                   6945: 
1.200     albertel 6946: sub check_for_error {
                   6947:     my ($r,$result)=@_;
                   6948:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6949: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6950:     }
                   6951: }
1.157     albertel 6952: 
1.423     albertel 6953: =pod
                   6954: 
                   6955: =item scantron_warning_screen
                   6956: 
1.424     albertel 6957:    Interstitial screen to make sure the operator has selected the
                   6958:    correct options before we start the validation phase.
                   6959: 
1.423     albertel 6960: =cut
                   6961: 
1.203     albertel 6962: sub scantron_warning_screen {
1.650     raeburn  6963:     my ($button_text,$symb)=@_;
1.257     albertel 6964:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  6965:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6966:     my $CODElist;
1.284     albertel 6967:     if ($scantron_config{'CODElocation'} &&
                   6968: 	$scantron_config{'CODEstart'} &&
                   6969: 	$scantron_config{'CODElength'}) {
                   6970: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   6971: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6972: 	$CODElist=
1.492     albertel 6973: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6974: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6975:     }
1.663     raeburn  6976:     my $lastbubblepoints;
                   6977:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6978:         $lastbubblepoints =
                   6979:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6980:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6981:     }
1.770     raeburn  6982:     return '
1.203     albertel 6983: <p>
1.492     albertel 6984: <span class="LC_warning">
1.705     raeburn  6985: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6986: </p>
                   6987: <table>
1.492     albertel 6988: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6989: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6990: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6991: </table>
1.680     raeburn  6992: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6993: '.&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  6994: ';
1.203     albertel 6995: }
                   6996: 
1.423     albertel 6997: =pod
                   6998: 
                   6999: =item scantron_do_warning
                   7000: 
1.424     albertel 7001:    Check if the operator has picked something for all required
                   7002:    fields. Error out if something is missing.
                   7003: 
1.423     albertel 7004: =cut
                   7005: 
1.203     albertel 7006: sub scantron_do_warning {
1.608     www      7007:     my ($r,$symb)=@_;
1.203     albertel 7008:     if (!$symb) {return '';}
1.324     albertel 7009:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7010:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7011:     if ( $env{'form.selectpage'} eq '' ||
                   7012: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7013: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7014: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7015: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7016: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7017: 	} 
1.257     albertel 7018: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7019: 	    $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  7020: 	}
1.257     albertel 7021: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7022: 	    $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  7023: 	}
1.237     albertel 7024:     } else {
1.650     raeburn  7025: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.770     raeburn  7026:         my ($checksec,@possibles) = &gradable_sections();
                   7027:         my $gradesections;
                   7028:         if ($checksec) {
                   7029:             my $file=$env{'form.scantron_selectfile'};
                   7030:             if (&valid_file($file)) {
                   7031:                 my %bysec = &scantron_get_sections();
                   7032:                 my $table;
                   7033:                 if ((keys(%bysec) > 1) || ((keys(%bysec) == 1) && ((keys(%bysec))[0] ne $checksec))) {
                   7034:                     $gradesections = &mt('Your current role is for section [_1].','<i>'.$checksec.'</i>').'<br />';
                   7035:                     $table = &Apache::loncommon::start_data_table()."\n".
                   7036:                              &Apache::loncommon::start_data_table_header_row().
                   7037:                              '<th>'.&mt('Section').'</th><th>'.&mt('Number of records').'</th>'.
                   7038:                               &Apache::loncommon::end_data_table_header_row()."\n";
                   7039:                     if ($bysec{'none'}) {
                   7040:                         $table .= &Apache::loncommon::start_data_table_row().
                   7041:                                   '<td>'.&mt('None').'</td><td>'.$bysec{'none'}.'</td>'.
                   7042:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7043:                     }
                   7044:                     foreach my $sec (sort { $a <=> $b } keys(%bysec)) {
                   7045:                         next if ($sec eq 'none');
                   7046:                         $table .= &Apache::loncommon::start_data_table_row().
                   7047:                                   '<td>'.$sec.'</td><td>'.$bysec{$sec}.'</td>'.
                   7048:                                   &Apache::loncommon::end_data_table_row()."\n";
                   7049:                     }
                   7050:                     $table .= &Apache::loncommon::end_data_table()."\n";
                   7051:                     $gradesections .= &mt('Sections represented in the bubblesheet data file (based on bubbled student IDs) are as follows:').
                   7052:                                       '<p>'.$table.'</p>';
                   7053:                     if (@possibles) {
                   7054:                         $gradesections .= '<p>'.
                   7055:                                           &mt('You have role(s) in [quant,_1,other section,other sections] with privileges to manage grades.',
                   7056:                                               scalar(@possibles)).'<br />'.
                   7057:                                           &mt('Check which of those section(s), in addition to section [_1], you wish to grade using this bubblesheet file:',
                   7058:                                               '<i>'.$checksec.'</i>').' ';
                   7059:                         foreach my $sec (sort {$a <=> $b } @possibles) {
                   7060:                             $gradesections .= '<label><input type="checkbox" name="scantron_othersections" value="'.$sec.'" />'.$sec.'</label>'.('&nbsp;'x2);
                   7061:                         }
                   7062:                         $gradesections .= '</p>';
                   7063:                     }
                   7064:                 }
                   7065:             } else {
                   7066:                 $gradesections = '<p class="LC_error">'.&mt('The selected file is unavailable').'</p>';
                   7067:             }
                   7068:         }
1.663     raeburn  7069:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7070: 	$r->print('
1.770     raeburn  7071: '.$warning.$gradesections.$bubbledbyhand.'
1.492     albertel 7072: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7073: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7074: ');
1.237     albertel 7075:     }
1.614     www      7076:     $r->print("</form><br />");
1.203     albertel 7077:     return '';
                   7078: }
                   7079: 
1.423     albertel 7080: =pod
                   7081: 
                   7082: =item scantron_form_start
                   7083: 
1.424     albertel 7084:     html hidden input for remembering all selected grading options
                   7085: 
1.423     albertel 7086: =cut
                   7087: 
1.203     albertel 7088: sub scantron_form_start {
                   7089:     my ($max_bubble)=@_;
                   7090:     my $result= <<SCANTRONFORM;
                   7091: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7092:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7093:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7094:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7095:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7096:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7097:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7098:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7099:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7100:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7101: SCANTRONFORM
1.447     foxr     7102: 
                   7103:   my $line = 0;
                   7104:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7105:        my $chunk =
                   7106: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7107:        $chunk .=
                   7108: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7109:        $chunk .= 
                   7110:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7111:        $chunk .=
                   7112:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7113:        $chunk .=
                   7114:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7115:        $result .= $chunk;
                   7116:        $line++;
1.691     raeburn  7117:     }
1.203     albertel 7118:     return $result;
                   7119: }
                   7120: 
1.423     albertel 7121: =pod
                   7122: 
                   7123: =item scantron_validate_file
                   7124: 
1.659     raeburn  7125:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7126: 
                   7127:     Also processes any necessary information resets that need to
                   7128:     occur before validation begins (ignore previous corrections,
                   7129:     restarting the skipped records processing)
                   7130: 
1.423     albertel 7131: =cut
                   7132: 
1.157     albertel 7133: sub scantron_validate_file {
1.608     www      7134:     my ($r,$symb) = @_;
1.157     albertel 7135:     if (!$symb) {return '';}
1.324     albertel 7136:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7137:     
1.703     bisitz   7138:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7139:     # them when doing the corrections reset
1.257     albertel 7140:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7141: 	&reset_skipping_status();
                   7142:     }
1.257     albertel 7143:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7144: 	&remember_current_skipped();
1.257     albertel 7145: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7146:     }
                   7147: 
1.257     albertel 7148:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7149: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7150: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7151: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7152: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7153:     }
1.200     albertel 7154: 
1.257     albertel 7155:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7156: 	&scantron_process_corrections($r);
                   7157:     }
1.770     raeburn  7158: 
                   7159:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');
                   7160:     my ($checksec,@gradable);
                   7161:     if ($env{'request.course.sec'}) {
                   7162:         ($checksec,my @possibles) = &gradable_sections();
                   7163:         if ($checksec) {
                   7164:             if (@possibles) {
                   7165:                 my @chosensecs = &Apache::loncommon::get_env_multiple('form.scantron_othersections');
                   7166:                 if (@chosensecs) {
                   7167:                     foreach my $sec (@chosensecs) {
                   7168:                         if (grep(/^\Q$sec\E$/,@possibles)) {
                   7169:                             unless (grep(/^\Q$sec\E$/,@gradable)) {
                   7170:                                 push(@gradable,$sec);
                   7171:                             }
                   7172:                         }
                   7173:                     }
                   7174:                 }
                   7175:             }
                   7176:             $r->print('<p><table>');
                   7177:             if (@gradable) {
                   7178:                 my @showsections = sort { $a <=> $b } (@gradable,$checksec);
                   7179:                 $r->print(
                   7180:                     '<tr><td><b>'.&mt('Sections to be Graded:').'</b></td><td>'.join(', ',@showsections).'</td></tr>');
                   7181:             } else {
                   7182:                 $r->print(
                   7183:                     '<tr><td><b>'.&mt('Section to be Graded:').'</b></td><td>'.$checksec.'</td></tr>');
                   7184:             }
                   7185:             $r->print('</table></p>');
                   7186:         }
                   7187:     }
                   7188:     $r->rflush();
                   7189: 
1.157     albertel 7190:     #get the student pick code ready
                   7191:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7192:     my $nav_error;
1.754     raeburn  7193:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7194:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7195:     if ($nav_error) {
                   7196:         $r->print(&navmap_errormsg());
                   7197:         return '';
                   7198:     }
1.203     albertel 7199:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7200:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7201:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7202:     }
1.157     albertel 7203:     $r->print($result);
                   7204:     
1.334     albertel 7205:     my @validate_phases=( 'sequence',
                   7206: 			  'ID',
1.157     albertel 7207: 			  'CODE',
                   7208: 			  'doublebubble',
                   7209: 			  'missingbubbles');
1.257     albertel 7210:     if (!$env{'form.validatepass'}) {
                   7211: 	$env{'form.validatepass'} = 0;
1.157     albertel 7212:     }
1.257     albertel 7213:     my $currentphase=$env{'form.validatepass'};
1.770     raeburn  7214:     my %skipbysec=();
1.448     foxr     7215: 
1.157     albertel 7216:     my $stop=0;
                   7217:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7218: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7219: 	$r->rflush();
1.691     raeburn  7220:      
1.157     albertel 7221: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7222: 	{
                   7223: 	    no strict 'refs';
1.770     raeburn  7224:             my @extras=();
                   7225:             if ($validate_phases[$currentphase] eq 'ID') {
                   7226:                 @extras = (\%skipbysec,$checksec,@gradable);
                   7227:             }
                   7228: 	    ($stop,$currentphase)=&$which($r,$currentphase,@extras);
1.157     albertel 7229: 	}
                   7230:     }
                   7231:     if (!$stop) {
1.650     raeburn  7232: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.770     raeburn  7233:         my $secinfo;
                   7234:         if (keys(%skipbysec) > 0) {
                   7235:             my $seclist = '<ul>';
                   7236:             foreach my $sec (sort { $a <=> $b } keys(%skipbysec)) {
                   7237:                 $seclist .= '<li>'.&mt('section [_1]: [_2]',$sec,$skipbysec{$sec}).'</li>';
                   7238:             }
                   7239:             $seclist .= '</ul>';
                   7240:             $secinfo = '<p class="LC_info">'.
                   7241:                        &mt('Numbers of records for students in sections not being graded [_1]',
                   7242:                            $seclist).
                   7243:                        '</p>';
                   7244:         }
1.542     raeburn  7245: 	$r->print(&mt('Validation process complete.').'<br />'.
1.770     raeburn  7246:                   $secinfo.$warning.
1.542     raeburn  7247:                   &mt('Perform verification for each student after storage of submissions?').
                   7248:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7249:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7250:                   ('&nbsp;'x3).'<label>'.
                   7251:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7252:                   '</label></span><br />'.
                   7253:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7254:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7255:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7256:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7257:     } else {
                   7258: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7259: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7260:     }
                   7261:     if ($stop) {
1.334     albertel 7262: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7263: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7264: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7265: 
1.650     raeburn  7266: 	    $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 7267: 	} else {
1.503     raeburn  7268:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7269: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7270:             } else {
1.539     riegler  7271:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7272:             }
1.492     albertel 7273: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7274: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7275: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7276: 	}
1.157     albertel 7277:     }
1.614     www      7278:     $r->print(" </form><br />");
1.157     albertel 7279:     return '';
                   7280: }
                   7281: 
1.423     albertel 7282: 
                   7283: =pod
                   7284: 
                   7285: =item scantron_remove_file
                   7286: 
1.659     raeburn  7287:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7288:    scantron_original_<filename> is never removed
                   7289: 
                   7290: 
1.423     albertel 7291: =cut
                   7292: 
1.200     albertel 7293: sub scantron_remove_file {
1.192     albertel 7294:     my ($which)=@_;
1.257     albertel 7295:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7296:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7297:     my $file='scantron_';
1.200     albertel 7298:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7299: 	$file.=$which.'_';
1.192     albertel 7300:     } else {
                   7301: 	return 'refused';
                   7302:     }
1.257     albertel 7303:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7304:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7305: }
                   7306: 
1.423     albertel 7307: 
                   7308: =pod
                   7309: 
                   7310: =item scantron_remove_scan_data
                   7311: 
1.659     raeburn  7312:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7313:    data file.  (In the case that both the are doing skipped records we need
                   7314:    to remember the old skipped lines for the time being so that element
                   7315:    persists for a while.)
                   7316: 
1.423     albertel 7317: =cut
                   7318: 
1.200     albertel 7319: sub scantron_remove_scan_data {
1.257     albertel 7320:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7321:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7322:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7323:     my @todelete;
1.257     albertel 7324:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7325:     foreach my $key (@keys) {
                   7326: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7327: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7328: 		$key=~/remember_skipping/) {
                   7329: 		next;
                   7330: 	    }
1.192     albertel 7331: 	    push(@todelete,$key);
                   7332: 	}
                   7333:     }
1.200     albertel 7334:     my $result;
1.192     albertel 7335:     if (@todelete) {
1.491     albertel 7336: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7337: 				       \@todelete,$cdom,$cname);
                   7338:     } else {
                   7339: 	$result = 'ok';
1.192     albertel 7340:     }
                   7341:     return $result;
                   7342: }
                   7343: 
1.423     albertel 7344: 
                   7345: =pod
                   7346: 
                   7347: =item scantron_getfile
                   7348: 
1.659     raeburn  7349:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7350:     the scan_data hash
                   7351:   
                   7352:   Arguments:
                   7353:     None
                   7354: 
                   7355:   Returns:
                   7356:     2 hash references
                   7357: 
                   7358:      - first one has 
                   7359:          orig      -
                   7360:          corrected -
                   7361:          skipped   -  each of which points to an array ref of the specified
                   7362:                       file broken up into individual lines
                   7363:          count     - number of scanlines
                   7364:  
                   7365:      - second is the scan_data hash possible keys are
1.425     albertel 7366:        ($number refers to scanline numbered $number and thus the key affects
                   7367:         only that scanline
                   7368:         $bubline refers to the specific bubble line element and the aspects
                   7369:         refers to that specific bubble line element)
                   7370: 
                   7371:        $number.user - username:domain to use
                   7372:        $number.CODE_ignore_dup 
                   7373:                     - ignore the duplicate CODE error 
                   7374:        $number.useCODE
                   7375:                     - use the CODE in the scanline as is
                   7376:        $number.no_bubble.$bubline
                   7377:                     - it is valid that there is no bubbled in bubble
                   7378:                       at $number $bubline
                   7379:        remember_skipping
                   7380:                     - a frozen hash containing keys of $number and values
                   7381:                       of either 
                   7382:                         1 - we are on a 'do skipped records pass' and plan
                   7383:                             on processing this line
                   7384:                         2 - we are on a 'do skipped records pass' and this
                   7385:                             scanline has been marked to skip yet again
1.424     albertel 7386: 
1.423     albertel 7387: =cut
                   7388: 
1.157     albertel 7389: sub scantron_getfile {
1.200     albertel 7390:     #FIXME really would prefer a scantron directory
1.257     albertel 7391:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7392:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7393:     my $lines;
                   7394:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7395: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7396:     my %scanlines;
                   7397:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7398:     my $temp=$scanlines{'orig'};
                   7399:     $scanlines{'count'}=$#$temp;
                   7400: 
                   7401:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7402: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7403:     if ($lines eq '-1') {
                   7404: 	$scanlines{'corrected'}=[];
                   7405:     } else {
                   7406: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7407:     }
                   7408:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7409: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7410:     if ($lines eq '-1') {
                   7411: 	$scanlines{'skipped'}=[];
                   7412:     } else {
                   7413: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7414:     }
1.175     albertel 7415:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7416:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7417:     my %scan_data = @tmp;
                   7418:     return (\%scanlines,\%scan_data);
                   7419: }
                   7420: 
1.423     albertel 7421: =pod
                   7422: 
                   7423: =item lonnet_putfile
                   7424: 
1.424     albertel 7425:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7426: 
                   7427:  Arguments:
                   7428:    $contents - data to store
                   7429:    $filename - filename to store $contents into
                   7430: 
                   7431:  Returns:
                   7432:    result value from &Apache::lonnet::finishuserfileupload
                   7433: 
1.423     albertel 7434: =cut
                   7435: 
1.157     albertel 7436: sub lonnet_putfile {
                   7437:     my ($contents,$filename)=@_;
1.257     albertel 7438:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7439:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7440:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7441:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7442: 
                   7443: }
                   7444: 
1.423     albertel 7445: =pod
                   7446: 
                   7447: =item scantron_putfile
                   7448: 
1.659     raeburn  7449:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7450:     scan_data hash. (Does not modify the original version only the
                   7451:     corrected and skipped versions.
                   7452: 
                   7453:  Arguments:
                   7454:     $scanlines - hash ref that looks like the first return value from
                   7455:                  &scantron_getfile()
                   7456:     $scan_data - hash ref that looks like the second return value from
                   7457:                  &scantron_getfile()
                   7458: 
1.423     albertel 7459: =cut
                   7460: 
1.157     albertel 7461: sub scantron_putfile {
                   7462:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7463:     #FIXME really would prefer a scantron directory
1.257     albertel 7464:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7465:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7466:     if ($scanlines) {
                   7467: 	my $prefix='scantron_';
1.157     albertel 7468: # no need to update orig, shouldn't change
                   7469: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7470: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7471: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7472: 			$prefix.'corrected_'.
1.257     albertel 7473: 			$env{'form.scantron_selectfile'});
1.200     albertel 7474: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7475: 			$prefix.'skipped_'.
1.257     albertel 7476: 			$env{'form.scantron_selectfile'});
1.200     albertel 7477:     }
1.175     albertel 7478:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7479: }
                   7480: 
1.423     albertel 7481: =pod
                   7482: 
                   7483: =item scantron_get_line
                   7484: 
1.424     albertel 7485:    Returns the correct version of the scanline
                   7486: 
                   7487:  Arguments:
                   7488:     $scanlines - hash ref that looks like the first return value from
                   7489:                  &scantron_getfile()
                   7490:     $scan_data - hash ref that looks like the second return value from
                   7491:                  &scantron_getfile()
                   7492:     $i         - number of the requested line (starts at 0)
                   7493: 
                   7494:  Returns:
                   7495:    A scanline, (either the original or the corrected one if it
                   7496:    exists), or undef if the requested scanline should be
                   7497:    skipped. (Either because it's an skipped scanline, or it's an
                   7498:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7499:    pass.
                   7500: 
1.423     albertel 7501: =cut
                   7502: 
1.157     albertel 7503: sub scantron_get_line {
1.200     albertel 7504:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7505:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7506:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7507:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7508:     return $scanlines->{'orig'}[$i]; 
                   7509: }
                   7510: 
1.423     albertel 7511: =pod
                   7512: 
                   7513: =item scantron_todo_count
                   7514: 
1.424     albertel 7515:     Counts the number of scanlines that need processing.
                   7516: 
                   7517:  Arguments:
                   7518:     $scanlines - hash ref that looks like the first return value from
                   7519:                  &scantron_getfile()
                   7520:     $scan_data - hash ref that looks like the second return value from
                   7521:                  &scantron_getfile()
                   7522: 
                   7523:  Returns:
                   7524:     $count - number of scanlines to process
                   7525: 
1.423     albertel 7526: =cut
                   7527: 
1.200     albertel 7528: sub get_todo_count {
                   7529:     my ($scanlines,$scan_data)=@_;
                   7530:     my $count=0;
                   7531:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7532: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7533: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7534: 	$count++;
                   7535:     }
                   7536:     return $count;
                   7537: }
                   7538: 
1.423     albertel 7539: =pod
                   7540: 
                   7541: =item scantron_put_line
                   7542: 
1.659     raeburn  7543:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7544:     data file.
                   7545: 
                   7546:  Arguments:
                   7547:     $scanlines - hash ref that looks like the first return value from
                   7548:                  &scantron_getfile()
                   7549:     $scan_data - hash ref that looks like the second return value from
                   7550:                  &scantron_getfile()
                   7551:     $i         - line number to update
                   7552:     $newline   - contents of the updated scanline
                   7553:     $skip      - if true make the line for skipping and update the
                   7554:                  'skipped' file
                   7555: 
1.423     albertel 7556: =cut
                   7557: 
1.157     albertel 7558: sub scantron_put_line {
1.200     albertel 7559:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7560:     if ($skip) {
                   7561: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7562: 	&start_skipping($scan_data,$i);
1.157     albertel 7563: 	return;
                   7564:     }
                   7565:     $scanlines->{'corrected'}[$i]=$newline;
                   7566: }
                   7567: 
1.423     albertel 7568: =pod
                   7569: 
                   7570: =item scantron_clear_skip
                   7571: 
1.424     albertel 7572:    Remove a line from the 'skipped' file
                   7573: 
                   7574:  Arguments:
                   7575:     $scanlines - hash ref that looks like the first return value from
                   7576:                  &scantron_getfile()
                   7577:     $scan_data - hash ref that looks like the second return value from
                   7578:                  &scantron_getfile()
                   7579:     $i         - line number to update
                   7580: 
1.423     albertel 7581: =cut
                   7582: 
1.376     albertel 7583: sub scantron_clear_skip {
                   7584:     my ($scanlines,$scan_data,$i)=@_;
                   7585:     if (exists($scanlines->{'skipped'}[$i])) {
                   7586: 	undef($scanlines->{'skipped'}[$i]);
                   7587: 	return 1;
                   7588:     }
                   7589:     return 0;
                   7590: }
                   7591: 
1.423     albertel 7592: =pod
                   7593: 
                   7594: =item scantron_filter_not_exam
                   7595: 
1.424     albertel 7596:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7597:    filter out resources that are not marked as 'exam' mode
                   7598: 
1.423     albertel 7599: =cut
                   7600: 
1.334     albertel 7601: sub scantron_filter_not_exam {
                   7602:     my ($curres)=@_;
                   7603:     
                   7604:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7605: 	# if the user has asked to not have either hidden
                   7606: 	# or 'randomout' controlled resources to be graded
                   7607: 	# don't include them
                   7608: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7609: 	    && $curres->randomout) {
                   7610: 	    return 0;
                   7611: 	}
                   7612: 	return 1;
                   7613:     }
                   7614:     return 0;
                   7615: }
                   7616: 
1.423     albertel 7617: =pod
                   7618: 
                   7619: =item scantron_validate_sequence
                   7620: 
1.424     albertel 7621:     Validates the selected sequence, checking for resource that are
                   7622:     not set to exam mode.
                   7623: 
1.423     albertel 7624: =cut
                   7625: 
1.334     albertel 7626: sub scantron_validate_sequence {
                   7627:     my ($r,$currentphase) = @_;
                   7628: 
                   7629:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7630:     unless (ref($navmap)) {
                   7631:         $r->print(&navmap_errormsg());
                   7632:         return (1,$currentphase);
                   7633:     }
1.334     albertel 7634:     my (undef,undef,$sequence)=
                   7635: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7636: 
                   7637:     my $map=$navmap->getResourceByUrl($sequence);
                   7638: 
                   7639:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7640:                                     value="ignore" />');
                   7641:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7642: 	my @resources=
                   7643: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7644: 	if (@resources) {
1.675     bisitz   7645: 	    $r->print(
                   7646:                 '<p class="LC_warning">'
                   7647:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7648:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7649:                    .' work correctly.')
                   7650:                .'</p>'
                   7651:             );
1.334     albertel 7652: 	    return (1,$currentphase);
                   7653: 	}
                   7654:     }
                   7655: 
                   7656:     return (0,$currentphase+1);
                   7657: }
                   7658: 
1.423     albertel 7659: 
                   7660: 
1.157     albertel 7661: sub scantron_validate_ID {
1.770     raeburn  7662:     my ($r,$currentphase,$skipbysec,$checksec,@gradable) = @_;
1.157     albertel 7663:     
                   7664:     #get student info
                   7665:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7666:     my %idmap=&username_to_idmap($classlist);
1.770     raeburn  7667:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.157     albertel 7668: 
                   7669:     #get scantron line setup
1.754     raeburn  7670:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7671:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7672: 
                   7673:     my $nav_error;
1.649     raeburn  7674:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7675:     if ($nav_error) {
                   7676:         $r->print(&navmap_errormsg());
                   7677:         return(1,$currentphase);
                   7678:     }
1.157     albertel 7679: 
                   7680:     my %found=('ids'=>{},'usernames'=>{});
1.770     raeburn  7681:     my $unsavedskips = 0;
1.157     albertel 7682:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7683: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7684: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7685: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7686: 						 $scan_data);
                   7687: 	my $id=$$scan_record{'scantron.ID'};
                   7688: 	my $found;
                   7689: 	foreach my $checkid (keys(%idmap)) {
                   7690: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7691: 	}
                   7692: 	if ($found) {
                   7693: 	    my $username=$idmap{$found};
1.770     raeburn  7694:             if ($checksec) {
                   7695:                 if (ref($classlist->{$username}) eq 'ARRAY') {
                   7696:                     my $stusec = $classlist->{$username}->[$secidx];
                   7697:                     if ($stusec ne $checksec) {
                   7698:                         unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7699:                             my $skip=1;
                   7700:                             &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7701:                             if (ref($skipbysec) eq 'HASH') {
                   7702:                                 if ($stusec eq '') {
                   7703:                                     $skipbysec->{'none'} ++;
                   7704:                                 } else {
                   7705:                                     $skipbysec->{$stusec} ++;
                   7706:                                 }
                   7707:                             }
                   7708:                             $unsavedskips ++;
                   7709:                             next;
                   7710:                         }
                   7711:                     }
                   7712:                 }
                   7713:             }
1.157     albertel 7714: 	    if ($found{'ids'}{$found}) {
                   7715: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7716: 					 $line,'duplicateID',$found);
1.770     raeburn  7717:                 if ($unsavedskips) {
                   7718:                     &scantron_putfile($scanlines,$scan_data);
                   7719:                     $unsavedskips = 0;
                   7720:                 }
1.194     albertel 7721: 		return(1,$currentphase);
1.157     albertel 7722: 	    } elsif ($found{'usernames'}{$username}) {
                   7723: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7724: 					 $line,'duplicateID',$username);
1.770     raeburn  7725:                 if ($unsavedskips) {
                   7726:                     &scantron_putfile($scanlines,$scan_data);
                   7727:                     $unsavedskips = 0;
                   7728:                 }
1.194     albertel 7729: 		return(1,$currentphase);
1.157     albertel 7730: 	    }
1.186     albertel 7731: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7732: 	    $found{'ids'}{$found}++;
                   7733: 	    $found{'usernames'}{$username}++;
                   7734: 	} else {
                   7735: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7736: 		my $username=&scan_data($scan_data,"$i.user");
1.770     raeburn  7737:                 if (($checksec && $username ne '')) {
                   7738:                     if (ref($classlist->{$username}) eq 'ARRAY') {
                   7739:                         my $stusec = $classlist->{$username}->[$secidx];
                   7740:                         if ($stusec ne $checksec) {
                   7741:                             unless ((@gradable > 0) && (grep(/^\Q$stusec\E$/,@gradable))) {
                   7742:                                 my $skip=1;
                   7743:                                 &scantron_put_line($scanlines,$scan_data,$i,$line,$skip);
                   7744:                                 if (ref($skipbysec) eq 'HASH') {
                   7745:                                     if ($stusec eq '') {
                   7746:                                         $skipbysec->{'none'} ++;
                   7747:                                     } else {
                   7748:                                         $skipbysec->{$stusec} ++;
                   7749:                                     }
                   7750:                                 }
                   7751:                                 $unsavedskips ++;
                   7752:                                 next;
                   7753:                             }
                   7754:                         }
                   7755:                     }
                   7756: 		} elsif (defined($username) && $found{'usernames'}{$username}) {
1.157     albertel 7757: 		    &scantron_get_correction($r,$i,$scan_record,
                   7758: 					     \%scantron_config,
                   7759: 					     $line,'duplicateID',$username);
1.770     raeburn  7760:                     if ($unsavedskips) {
                   7761:                         &scantron_putfile($scanlines,$scan_data);
                   7762:                         $unsavedskips = 0;
                   7763:                     }
1.194     albertel 7764: 		    return(1,$currentphase);
1.157     albertel 7765: 		} elsif (!defined($username)) {
                   7766: 		    &scantron_get_correction($r,$i,$scan_record,
                   7767: 					     \%scantron_config,
                   7768: 					     $line,'incorrectID');
1.770     raeburn  7769:                     if ($unsavedskips) {
                   7770:                         &scantron_putfile($scanlines,$scan_data);
                   7771:                         $unsavedskips = 0;
                   7772:                     }
1.194     albertel 7773: 		    return(1,$currentphase);
1.157     albertel 7774: 		}
                   7775: 		$found{'usernames'}{$username}++;
                   7776: 	    } else {
                   7777: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7778: 					 $line,'incorrectID');
1.770     raeburn  7779:                 if ($unsavedskips) {
                   7780:                     &scantron_putfile($scanlines,$scan_data);
                   7781:                     $unsavedskips = 0;
                   7782:                 }
1.194     albertel 7783: 		return(1,$currentphase);
1.157     albertel 7784: 	    }
                   7785: 	}
                   7786:     }
1.770     raeburn  7787:     if ($unsavedskips) {
                   7788:         &scantron_putfile($scanlines,$scan_data);
                   7789:         $unsavedskips = 0;
                   7790:     }
1.157     albertel 7791:     return (0,$currentphase+1);
                   7792: }
                   7793: 
1.770     raeburn  7794: sub scantron_get_sections {
                   7795:     my %bysec;
                   7796:     if ($env{'form.scantron_format'} ne '') {
                   7797:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
                   7798:         my ($scanlines,$scan_data)=&scantron_getfile();
                   7799:         my $classlist=&Apache::loncoursedata::get_classlist();
                   7800:         my %idmap=&username_to_idmap($classlist);
                   7801:         foreach my $key (keys(%idmap)) {
                   7802:             my $lckey = lc($key);
                   7803:             $idmap{$lckey} = $idmap{$key};
                   7804:         }
                   7805:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   7806:         for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7807:             my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7808:             if ($line=~/^[\s\cz]*$/) { next; }
                   7809:             my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7810:                                                      $scan_data);
                   7811:             my $id=lc($$scan_record{'scantron.ID'});
                   7812:             if (exists($idmap{$id})) {
                   7813:                 if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   7814:                     my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   7815:                     if ($stusec eq '') {
                   7816:                         $bysec{'none'} ++;
                   7817:                     } else {
                   7818:                         $bysec{$stusec} ++;
                   7819:                     }
                   7820:                 }
                   7821:             }
                   7822:         }
                   7823:     }
                   7824:     return %bysec;
                   7825: }
1.423     albertel 7826: 
1.157     albertel 7827: sub scantron_get_correction {
1.691     raeburn  7828:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7829:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7830: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7831: #to show both the current line and the previous one and allow skipping
                   7832: #the previous one or the current one
                   7833: 
1.333     albertel 7834:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7835:         $r->print(
                   7836:             '<p class="LC_warning">'
                   7837:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7838:                 "<b>$error</b>",
                   7839:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7840:            ."</p> \n");
1.157     albertel 7841:     } else {
1.658     bisitz   7842:         $r->print(
                   7843:             '<p class="LC_warning">'
                   7844:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7845:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7846:            ."</p> \n");
                   7847:     }
                   7848:     my $message =
                   7849:         '<p>'
                   7850:        .&mt('The ID on the form is [_1]',
                   7851:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7852:        .'<br />'
1.665     raeburn  7853:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7854:             $$scan_record{'scantron.LastName'},
                   7855:             $$scan_record{'scantron.FirstName'})
                   7856:        .'</p>';
1.242     albertel 7857: 
1.157     albertel 7858:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7859:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7860:                            # Array populated for doublebubble or
                   7861:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7862:                            # to validate radio button checking   
                   7863: 
1.157     albertel 7864:     if ($error =~ /ID$/) {
1.186     albertel 7865: 	if ($error eq 'incorrectID') {
1.658     bisitz   7866:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7867: 		      "</p>\n");
1.157     albertel 7868: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7869:             $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 7870: 	}
1.242     albertel 7871: 	$r->print($message);
1.492     albertel 7872: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7873: 	$r->print("\n<ul><li> ");
                   7874: 	#FIXME it would be nice if this sent back the user ID and
                   7875: 	#could do partial userID matches
                   7876: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7877: 				       'scantron_username','scantron_domain'));
                   7878: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7879: 	$r->print("\n:\n".
1.257     albertel 7880: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7881: 
                   7882: 	$r->print('</li>');
1.186     albertel 7883:     } elsif ($error =~ /CODE$/) {
                   7884: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7885: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7886: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7887: 	    $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 7888: 	}
1.658     bisitz   7889: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7890: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7891:                  ."</p>\n");
1.242     albertel 7892: 	$r->print($message);
1.658     bisitz   7893: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7894: 	$r->print("\n<br /> ");
1.194     albertel 7895: 	my $i=0;
1.273     albertel 7896: 	if ($error eq 'incorrectCODE' 
                   7897: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7898: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7899: 	    if ($closest > 0) {
                   7900: 		foreach my $testcode (@{$closest}) {
                   7901: 		    my $checked='';
1.569     bisitz   7902: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7903: 		    $r->print("
                   7904:    <label>
1.569     bisitz   7905:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7906:        ".&mt("Use the similar CODE [_1] instead.",
                   7907: 	    "<b><tt>".$testcode."</tt></b>")."
                   7908:     </label>
                   7909:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7910: 		    $r->print("\n<br />");
                   7911: 		    $i++;
                   7912: 		}
1.194     albertel 7913: 	    }
                   7914: 	}
1.273     albertel 7915: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7916: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7917: 	    $r->print("
                   7918:     <label>
1.569     bisitz   7919:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7920:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7921: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7922:     </label>");
1.273     albertel 7923: 	    $r->print("\n<br />");
                   7924: 	}
1.194     albertel 7925: 
1.597     wenzelju 7926: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7927: function change_radio(field) {
1.190     albertel 7928:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7929:     var i;
                   7930:     for (i=0;i<slct.length;i++) {
                   7931:         if (slct[i].value==field) { slct[i].checked=true; }
                   7932:     }
                   7933: }
                   7934: ENDSCRIPT
1.187     albertel 7935: 	my $href="/adm/pickcode?".
1.359     www      7936: 	   "form=".&escape("scantronupload").
                   7937: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7938: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7939: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7940: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7941: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7942: 	    $r->print("
                   7943:     <label>
                   7944:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7945:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7946: 	     "<a target='_blank' href='$href'>","</a>")."
                   7947:     </label> 
1.558     bisitz   7948:     ".&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 7949: 	    $r->print("\n<br />");
                   7950: 	}
1.492     albertel 7951: 	$r->print("
                   7952:     <label>
                   7953:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7954:        ".&mt("Use [_1] as the CODE.",
                   7955: 	     "</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 7956: 	$r->print("\n<br /><br />");
1.157     albertel 7957:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7958: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7959: 
                   7960: 	# The form field scantron_questions is acutally a list of line numbers.
                   7961: 	# represented by this form so:
                   7962: 
1.691     raeburn  7963: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7964:                                                 $respnumlookup,$startline);
1.497     foxr     7965: 
1.157     albertel 7966: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7967: 		  $line_list.'" />');
1.242     albertel 7968: 	$r->print($message);
1.492     albertel 7969: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7970: 	foreach my $question (@{$arg}) {
1.503     raeburn  7971: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7972:                                                    $scan_record, $error,
                   7973:                                                    $randomorder,$randompick,
                   7974:                                                    $respnumlookup,$startline);
1.524     raeburn  7975:             push(@lines_to_correct,@linenums);
1.157     albertel 7976: 	}
1.503     raeburn  7977:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7978:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7979: 	$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 7980: 	$r->print($message);
1.492     albertel 7981: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7982: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7983: 
1.503     raeburn  7984: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7985: 	# a list of question numbers. Therefore:
                   7986: 	#
1.691     raeburn  7987: 
                   7988: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7989:                                                 $respnumlookup,$startline);
1.497     foxr     7990: 
1.157     albertel 7991: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7992: 		  $line_list.'" />');
1.157     albertel 7993: 	foreach my $question (@{$arg}) {
1.503     raeburn  7994: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7995:                                                    $scan_record, $error,
                   7996:                                                    $randomorder,$randompick,
                   7997:                                                    $respnumlookup,$startline);
1.524     raeburn  7998:             push(@lines_to_correct,@linenums);
1.157     albertel 7999: 	}
1.503     raeburn  8000:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 8001:     } else {
                   8002: 	$r->print("\n<ul>");
                   8003:     }
                   8004:     $r->print("\n</li></ul>");
1.497     foxr     8005: }
                   8006: 
1.503     raeburn  8007: sub verify_bubbles_checked {
                   8008:     my (@ansnums) = @_;
                   8009:     my $ansnumstr = join('","',@ansnums);
                   8010:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  8011:     &js_escape(\$warning);
1.767     raeburn  8012:     my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
1.503     raeburn  8013: function verify_bubble_radio(form) {
                   8014:     var ansnumArray = new Array ("$ansnumstr");
                   8015:     var need_bubble_count = 0;
                   8016:     for (var i=0; i<ansnumArray.length; i++) {
                   8017:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   8018:             var bubble_picked = 0; 
                   8019:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   8020:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   8021:                     bubble_picked = 1;
                   8022:                 }
                   8023:             }
                   8024:             if (bubble_picked == 0) {
                   8025:                 need_bubble_count ++;
                   8026:             }
                   8027:         }
                   8028:     }
                   8029:     if (need_bubble_count) {
                   8030:         alert("$warning");
                   8031:         return;
                   8032:     }
                   8033:     form.submit(); 
                   8034: }
                   8035: ENDSCRIPT
                   8036:     return $output;
                   8037: }
                   8038: 
1.497     foxr     8039: =pod
                   8040: 
                   8041: =item  questions_to_line_list
1.157     albertel 8042: 
1.497     foxr     8043: Converts a list of questions into a string of comma separated
                   8044: line numbers in the answer sheet used by the questions.  This is
                   8045: used to fill in the scantron_questions form field.
                   8046: 
                   8047:   Arguments:
                   8048:      questions    - Reference to an array of questions.
1.691     raeburn  8049:      randomorder  - True if randomorder in use.
                   8050:      randompick   - True if randompick in use.
                   8051:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8052:                      for current line to question number used for same question
                   8053:                      in "Master Seqence" (as seen by Course Coordinator).
                   8054:      startline    - Reference to hash where key is question number (0 is first)
                   8055:                     and key is number of first bubble line for current student
                   8056:                     or code-based randompick and/or randomorder.
1.693     raeburn  8057: 
1.497     foxr     8058: =cut
                   8059: 
                   8060: 
                   8061: sub questions_to_line_list {
1.691     raeburn  8062:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     8063:     my @lines;
                   8064: 
1.503     raeburn  8065:     foreach my $item (@{$questions}) {
                   8066:         my $question = $item;
                   8067:         my ($first,$count,$last);
                   8068:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   8069:             $question = $1;
                   8070:             my $subquestion = $2;
1.691     raeburn  8071:             my $responsenum = $question-1;
                   8072:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8073:                 $responsenum = $respnumlookup->{$question-1};
                   8074:                 if (ref($startline) eq 'HASH') {
                   8075:                     $first = $startline->{$question-1} + 1;
                   8076:                 }
                   8077:             } else {
                   8078:                 $first = $first_bubble_line{$responsenum} + 1;
                   8079:             }
                   8080:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8081:             my $subcount = 1;
                   8082:             while ($subcount<$subquestion) {
                   8083:                 $first += $subans[$subcount-1];
                   8084:                 $subcount ++;
                   8085:             }
                   8086:             $count = $subans[$subquestion-1];
                   8087:         } else {
1.691     raeburn  8088:             my $responsenum = $question-1;
                   8089:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8090:                 $responsenum = $respnumlookup->{$question-1};
                   8091:                 if (ref($startline) eq 'HASH') {
                   8092:                     $first = $startline->{$question-1} + 1;
                   8093:                 }
                   8094:             } else {
                   8095:                 $first = $first_bubble_line{$responsenum} + 1;
                   8096:             }
                   8097: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8098:         }
1.506     raeburn  8099:         $last = $first+$count-1;
1.503     raeburn  8100:         push(@lines, ($first..$last));
1.497     foxr     8101:     }
                   8102:     return join(',', @lines);
                   8103: }
                   8104: 
                   8105: =pod 
                   8106: 
                   8107: =item prompt_for_corrections
                   8108: 
                   8109: Prompts for a potentially multiline correction to the
                   8110: user's bubbling (factors out common code from scantron_get_correction
                   8111: for multi and missing bubble cases).
                   8112: 
                   8113:  Arguments:
                   8114:    $r           - Apache request object.
                   8115:    $question    - The question number to prompt for.
                   8116:    $scan_config - The scantron file configuration hash.
                   8117:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  8118:    $error       - Type of error
1.691     raeburn  8119:    $randomorder - True if randomorder in use.
                   8120:    $randompick  - True if randompick in use.
                   8121:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   8122:                     for current line to question number used for same question
                   8123:                     in "Master Seqence" (as seen by Course Coordinator).
                   8124:    $startline   - Reference to hash where key is question number (0 is first)
                   8125:                   and value is number of first bubble line for current student
                   8126:                   or code-based randompick and/or randomorder.
                   8127: 
1.497     foxr     8128: 
                   8129:  Implicit inputs:
                   8130:    %bubble_lines_per_response   - Starting line numbers for each question.
                   8131:                                   Numbered from 0 (but question numbers are from
                   8132:                                   1.
                   8133:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  8134:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   8135:                                   type problems render as separate sub-questions, 
1.503     raeburn  8136:                                   in exam mode. This hash contains a 
                   8137:                                   comma-separated list of the lines per 
                   8138:                                   sub-question.
1.510     raeburn  8139:    %responsetype_per_response   - essayresponse, formularesponse,
                   8140:                                   stringresponse, imageresponse, reactionresponse,
                   8141:                                   and organicresponse type problem parts can have
1.503     raeburn  8142:                                   multiple lines per response if the weight
                   8143:                                   assigned exceeds 10.  In this case, only
                   8144:                                   one bubble per line is permitted, but more 
                   8145:                                   than one line might contain bubbles, e.g.
                   8146:                                   bubbling of: line 1 - J, line 2 - J, 
                   8147:                                   line 3 - B would assign 22 points.  
1.497     foxr     8148: 
                   8149: =cut
                   8150: 
                   8151: sub prompt_for_corrections {
1.691     raeburn  8152:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8153:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8154:     my ($current_line,$lines);
                   8155:     my @linenums;
                   8156:     my $questionnum = $question;
1.691     raeburn  8157:     my ($first,$responsenum);
1.503     raeburn  8158:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8159:         $question = $1;
                   8160:         my $subquestion = $2;
1.691     raeburn  8161:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8162:             $responsenum = $respnumlookup->{$question-1};
                   8163:             if (ref($startline) eq 'HASH') {
                   8164:                 $first = $startline->{$question-1};
                   8165:             }
                   8166:         } else {
                   8167:             $responsenum = $question-1;
1.714     raeburn  8168:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  8169:         }
                   8170:         $current_line = $first + 1 ;
                   8171:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8172:         my $subcount = 1;
                   8173:         while ($subcount<$subquestion) {
                   8174:             $current_line += $subans[$subcount-1];
                   8175:             $subcount ++;
                   8176:         }
                   8177:         $lines = $subans[$subquestion-1];
                   8178:     } else {
1.691     raeburn  8179:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8180:             $responsenum = $respnumlookup->{$question-1};
                   8181:             if (ref($startline) eq 'HASH') { 
                   8182:                 $first = $startline->{$question-1};
                   8183:             }
                   8184:         } else {
                   8185:             $responsenum = $question-1;
                   8186:             $first = $first_bubble_line{$responsenum};
                   8187:         }
                   8188:         $current_line = $first + 1;
                   8189:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8190:     }
1.497     foxr     8191:     if ($lines > 1) {
1.503     raeburn  8192:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8193:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8194:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8195:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8196:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8197:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8198:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8199:             $r->print(
                   8200:                 &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)
                   8201:                .'<br /><br />'
                   8202:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8203:                .'<br />'
                   8204:                .&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.')
                   8205:                .'<br />'
                   8206:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8207:                .'<br /><br />'
                   8208:             );
1.503     raeburn  8209:         } else {
                   8210:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8211:         }
1.497     foxr     8212:     }
                   8213:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8214:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8215: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8216: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8217:         push(@linenums,$current_line);
1.497     foxr     8218: 	$current_line++;
                   8219:     }
                   8220:     if ($lines > 1) {
                   8221: 	$r->print("<hr /><br />");
                   8222:     }
1.503     raeburn  8223:     return @linenums;
1.157     albertel 8224: }
1.423     albertel 8225: 
                   8226: =pod
                   8227: 
                   8228: =item scantron_bubble_selector
                   8229:   
                   8230:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8231:    possibly showing the existing the selected bubbles if known
1.423     albertel 8232: 
                   8233:  Arguments:
                   8234:     $r           - Apache request object
1.754     raeburn  8235:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8236:     $line        - Number of the line being displayed.
1.503     raeburn  8237:     $questionnum - Question number (may include subquestion)
                   8238:     $error       - Type of error.
1.497     foxr     8239:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8240: 
                   8241: =cut
                   8242: 
1.157     albertel 8243: sub scantron_bubble_selector {
1.503     raeburn  8244:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8245:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8246: 
                   8247:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8248:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8249:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8250:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8251:             $max=$$scan_config{'BubblesPerRow'};
                   8252:             if (($scmode eq 'number') && ($max > 10)) {
                   8253:                 $max = 10;
                   8254:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8255:                 $max = 26;
                   8256:             }
                   8257:         } else {
                   8258:             $max = 10;
                   8259:         }
                   8260:     }
1.274     albertel 8261: 
1.157     albertel 8262:     my @alphabet=('A'..'Z');
1.503     raeburn  8263:     $r->print(&Apache::loncommon::start_data_table().
                   8264:               &Apache::loncommon::start_data_table_row());
                   8265:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8266:     for (my $i=0;$i<$max+1;$i++) {
                   8267: 	$r->print("\n".'<td align="center">');
                   8268: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8269: 	else { $r->print('&nbsp;'); }
                   8270: 	$r->print('</td>');
                   8271:     }
1.503     raeburn  8272:     $r->print(&Apache::loncommon::end_data_table_row().
                   8273:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8274:     for (my $i=0;$i<$max;$i++) {
                   8275: 	$r->print("\n".
                   8276: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8277: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8278:     }
1.503     raeburn  8279:     my $nobub_checked = ' ';
                   8280:     if ($error eq 'missingbubble') {
                   8281:         $nobub_checked = ' checked = "checked" ';
                   8282:     }
                   8283:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8284: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8285:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8286:               $line.'" value="'.$questionnum.'" /></td>');
                   8287:     $r->print(&Apache::loncommon::end_data_table_row().
                   8288:               &Apache::loncommon::end_data_table());
1.157     albertel 8289: }
                   8290: 
1.423     albertel 8291: =pod
                   8292: 
                   8293: =item num_matches
                   8294: 
1.424     albertel 8295:    Counts the number of characters that are the same between the two arguments.
                   8296: 
                   8297:  Arguments:
                   8298:    $orig - CODE from the scanline
                   8299:    $code - CODE to match against
                   8300: 
                   8301:  Returns:
                   8302:    $count - integer count of the number of same characters between the
                   8303:             two arguments
                   8304: 
1.423     albertel 8305: =cut
                   8306: 
1.194     albertel 8307: sub num_matches {
                   8308:     my ($orig,$code) = @_;
                   8309:     my @code=split(//,$code);
                   8310:     my @orig=split(//,$orig);
                   8311:     my $same=0;
                   8312:     for (my $i=0;$i<scalar(@code);$i++) {
                   8313: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8314:     }
                   8315:     return $same;
                   8316: }
                   8317: 
1.423     albertel 8318: =pod
                   8319: 
                   8320: =item scantron_get_closely_matching_CODEs
                   8321: 
1.424     albertel 8322:    Cycles through all CODEs and finds the set that has the greatest
                   8323:    number of same characters as the provided CODE
                   8324: 
                   8325:  Arguments:
                   8326:    $allcodes - hash ref returned by &get_codes()
                   8327:    $CODE     - CODE from the current scanline
                   8328: 
                   8329:  Returns:
                   8330:    2 element list
                   8331:     - first elements is number of how closely matching the best fit is 
                   8332:       (5 means best set has 5 matching characters)
                   8333:     - second element is an arrary ref containing the set of valid CODEs
                   8334:       that best fit the passed in CODE
                   8335: 
1.423     albertel 8336: =cut
                   8337: 
1.194     albertel 8338: sub scantron_get_closely_matching_CODEs {
                   8339:     my ($allcodes,$CODE)=@_;
                   8340:     my @CODEs;
                   8341:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8342: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8343:     }
                   8344: 
                   8345:     return ($#CODEs,$CODEs[-1]);
                   8346: }
                   8347: 
1.423     albertel 8348: =pod
                   8349: 
                   8350: =item get_codes
                   8351: 
1.424     albertel 8352:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8353:    set of remembered CODEs.
                   8354: 
                   8355:  Arguments:
                   8356:   $old_name - name of the set of remembered CODEs
                   8357:   $cdom     - domain of the course
                   8358:   $cnum     - internal course name
                   8359: 
                   8360:  Returns:
                   8361:   %allcodes - keys are the valid CODEs, values are all 1
                   8362: 
1.423     albertel 8363: =cut
                   8364: 
1.194     albertel 8365: sub get_codes {
1.280     foxr     8366:     my ($old_name, $cdom, $cnum) = @_;
                   8367:     if (!$old_name) {
                   8368: 	$old_name=$env{'form.scantron_CODElist'};
                   8369:     }
                   8370:     if (!$cdom) {
                   8371: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8372:     }
                   8373:     if (!$cnum) {
                   8374: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8375:     }
1.278     albertel 8376:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8377: 				    $cdom,$cnum);
                   8378:     my %allcodes;
                   8379:     if ($result{"type\0$old_name"} eq 'number') {
                   8380: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8381:     } else {
                   8382: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8383:     }
1.194     albertel 8384:     return %allcodes;
                   8385: }
                   8386: 
1.423     albertel 8387: =pod
                   8388: 
                   8389: =item scantron_validate_CODE
                   8390: 
1.424     albertel 8391:    Validates all scanlines in the selected file to not have any
                   8392:    invalid or underspecified CODEs and that none of the codes are
                   8393:    duplicated if this was requested.
                   8394: 
1.423     albertel 8395: =cut
                   8396: 
1.157     albertel 8397: sub scantron_validate_CODE {
                   8398:     my ($r,$currentphase) = @_;
1.754     raeburn  8399:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8400:     if ($scantron_config{'CODElocation'} &&
                   8401: 	$scantron_config{'CODEstart'} &&
                   8402: 	$scantron_config{'CODElength'}) {
1.257     albertel 8403: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8404: 	    &FIXME_blow_up()
                   8405: 	}
                   8406:     } else {
                   8407: 	return (0,$currentphase+1);
                   8408:     }
                   8409:     
                   8410:     my %usedCODEs;
                   8411: 
1.194     albertel 8412:     my %allcodes=&get_codes();
1.186     albertel 8413: 
1.582     raeburn  8414:     my $nav_error;
1.649     raeburn  8415:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8416:     if ($nav_error) {
                   8417:         $r->print(&navmap_errormsg());
                   8418:         return(1,$currentphase);
                   8419:     }
1.447     foxr     8420: 
1.186     albertel 8421:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8422:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8423: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8424: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8425: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8426: 						 $scan_data);
                   8427: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8428: 	my $error=0;
1.224     albertel 8429: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8430: 	    &scantron_get_correction($r,$i,$scan_record,
                   8431: 				     \%scantron_config,
                   8432: 				     $line,'incorrectCODE',\%allcodes);
                   8433: 	    return(1,$currentphase);
                   8434: 	}
1.221     albertel 8435: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8436: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8437: 	    &scantron_get_correction($r,$i,$scan_record,
                   8438: 				     \%scantron_config,
1.194     albertel 8439: 				     $line,'incorrectCODE',\%allcodes);
                   8440: 	    return(1,$currentphase);
1.186     albertel 8441: 	}
1.214     albertel 8442: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8443: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8444: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8445: 	    &scantron_get_correction($r,$i,$scan_record,
                   8446: 				     \%scantron_config,
1.194     albertel 8447: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8448: 	    return(1,$currentphase);
1.186     albertel 8449: 	}
1.524     raeburn  8450: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8451:     }
1.157     albertel 8452:     return (0,$currentphase+1);
                   8453: }
                   8454: 
1.423     albertel 8455: =pod
                   8456: 
                   8457: =item scantron_validate_doublebubble
                   8458: 
1.424     albertel 8459:    Validates all scanlines in the selected file to not have any
                   8460:    bubble lines with multiple bubbles marked.
                   8461: 
1.423     albertel 8462: =cut
                   8463: 
1.157     albertel 8464: sub scantron_validate_doublebubble {
                   8465:     my ($r,$currentphase) = @_;
                   8466:     #get student info
                   8467:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8468:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8469:     my (undef,undef,$sequence)=
                   8470:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8471: 
                   8472:     #get scantron line setup
1.754     raeburn  8473:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8474:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8475: 
                   8476:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8477:     unless (ref($navmap)) {
                   8478:         $r->print(&navmap_errormsg());
                   8479:         return(1,$currentphase);
                   8480:     }
                   8481:     my $map=$navmap->getResourceByUrl($sequence);
                   8482:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8483:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8484:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8485:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8486: 
1.583     raeburn  8487:     my $nav_error;
1.691     raeburn  8488:     if (ref($map)) {
                   8489:         $randomorder = $map->randomorder();
                   8490:         $randompick = $map->randompick();
                   8491:         if ($randomorder || $randompick) {
                   8492:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8493:             if ($nav_error) {
                   8494:                 $r->print(&navmap_errormsg());
                   8495:                 return(1,$currentphase);
                   8496:             }
                   8497:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8498:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8499:         }
                   8500:     } else {
                   8501:         $r->print(&navmap_errormsg());
                   8502:         return(1,$currentphase);
                   8503:     }
                   8504: 
1.649     raeburn  8505:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8506:     if ($nav_error) {
                   8507:         $r->print(&navmap_errormsg());
                   8508:         return(1,$currentphase);
                   8509:     }
1.447     foxr     8510: 
1.157     albertel 8511:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8512: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8513: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8514: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8515: 						 $scan_data,undef,\%idmap,$randomorder,
                   8516:                                                  $randompick,$sequence,\@master_seq,
                   8517:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8518:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8519: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8520: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8521: 				 'doublebubble',
1.691     raeburn  8522: 				 $$scan_record{'scantron.doubleerror'},
                   8523:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8524:     	return (1,$currentphase);
                   8525:     }
                   8526:     return (0,$currentphase+1);
                   8527: }
                   8528: 
1.423     albertel 8529: 
1.503     raeburn  8530: sub scantron_get_maxbubble {
1.649     raeburn  8531:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8532:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8533: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8534: 	&restore_bubble_lines();
1.257     albertel 8535: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8536:     }
1.330     albertel 8537: 
1.447     foxr     8538:     my (undef, undef, $sequence) =
1.257     albertel 8539: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8540: 
1.447     foxr     8541:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8542:     unless (ref($navmap)) {
                   8543:         if (ref($nav_error)) {
                   8544:             $$nav_error = 1;
                   8545:         }
1.591     raeburn  8546:         return;
1.582     raeburn  8547:     }
1.191     albertel 8548:     my $map=$navmap->getResourceByUrl($sequence);
                   8549:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8550:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8551: 
                   8552:     &Apache::lonxml::clear_problem_counter();
                   8553: 
1.557     raeburn  8554:     my $uname       = $env{'user.name'};
                   8555:     my $udom        = $env{'user.domain'};
1.435     foxr     8556:     my $cid         = $env{'request.course.id'};
                   8557:     my $total_lines = 0;
                   8558:     %bubble_lines_per_response = ();
1.447     foxr     8559:     %first_bubble_line         = ();
1.503     raeburn  8560:     %subdivided_bubble_lines   = ();
                   8561:     %responsetype_per_response = ();
1.691     raeburn  8562:     %masterseq_id_responsenum  = ();
1.554     raeburn  8563: 
1.447     foxr     8564:     my $response_number = 0;
                   8565:     my $bubble_line     = 0;
1.191     albertel 8566:     foreach my $resource (@resources) {
1.691     raeburn  8567:         my $resid = $resource->id(); 
1.672     raeburn  8568:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8569:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8570:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8571: 	    foreach my $part_id (@{$parts}) {
                   8572:                 my $lines;
                   8573: 
                   8574: 	        # TODO - make this a persistent hash not an array.
                   8575: 
                   8576:                 # optionresponse, matchresponse and rankresponse type items 
                   8577:                 # render as separate sub-questions in exam mode.
                   8578:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8579:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8580:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8581:                     my ($numbub,$numshown);
                   8582:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8583:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8584:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8585:                         }
                   8586:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8587:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8588:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8589:                         }
                   8590:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8591:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8592:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8593:                         }
                   8594:                     }
                   8595:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8596:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8597:                     }
1.649     raeburn  8598:                     my $bubbles_per_row =
                   8599:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8600:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8601:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8602:                         $inner_bubble_lines++;
                   8603:                     }
                   8604:                     for (my $i=0; $i<$numshown; $i++) {
                   8605:                         $subdivided_bubble_lines{$response_number} .= 
                   8606:                             $inner_bubble_lines.',';
                   8607:                     }
                   8608:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8609:                     $lines = $numshown * $inner_bubble_lines;
                   8610:                 } else {
                   8611:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8612:                 }
1.542     raeburn  8613: 
                   8614:                 $first_bubble_line{$response_number} = $bubble_line;
                   8615: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8616:                 $responsetype_per_response{$response_number} = 
                   8617:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8618:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8619: 	        $response_number++;
                   8620: 
                   8621: 	        $bubble_line +=  $lines;
                   8622: 	        $total_lines +=  $lines;
                   8623: 	    }
                   8624:         }
                   8625:     }
1.552     raeburn  8626:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8627: 
                   8628:     &save_bubble_lines();
                   8629:     $env{'form.scantron_maxbubble'} =
                   8630: 	$total_lines;
                   8631:     return $env{'form.scantron_maxbubble'};
                   8632: }
1.523     raeburn  8633: 
1.649     raeburn  8634: sub bubblesheet_bubbles_per_row {
                   8635:     my ($scantron_config) = @_;
                   8636:     my $bubbles_per_row;
                   8637:     if (ref($scantron_config) eq 'HASH') {
                   8638:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8639:     }
                   8640:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8641:         $bubbles_per_row = 10;
                   8642:     }
                   8643:     return $bubbles_per_row;
                   8644: }
                   8645: 
1.157     albertel 8646: sub scantron_validate_missingbubbles {
                   8647:     my ($r,$currentphase) = @_;
                   8648:     #get student info
                   8649:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8650:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8651:     my (undef,undef,$sequence)=
                   8652:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8653: 
                   8654:     #get scantron line setup
1.754     raeburn  8655:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8656:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8657: 
                   8658:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8659:     unless (ref($navmap)) {
                   8660:         $r->print(&navmap_errormsg());
                   8661:         return(1,$currentphase);
                   8662:     }
                   8663: 
                   8664:     my $map=$navmap->getResourceByUrl($sequence);
                   8665:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8666:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8667:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8668:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8669: 
1.582     raeburn  8670:     my $nav_error;
1.691     raeburn  8671:     if (ref($map)) {
                   8672:         $randomorder = $map->randomorder();
                   8673:         $randompick = $map->randompick();
                   8674:         if ($randomorder || $randompick) {
                   8675:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8676:             if ($nav_error) {
                   8677:                 $r->print(&navmap_errormsg());
                   8678:                 return(1,$currentphase);
                   8679:             }
                   8680:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8681:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8682:         }
                   8683:     } else {
                   8684:         $r->print(&navmap_errormsg());
                   8685:         return(1,$currentphase);
                   8686:     }
                   8687: 
                   8688: 
1.649     raeburn  8689:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8690:     if ($nav_error) {
1.691     raeburn  8691:         $r->print(&navmap_errormsg());
1.693     raeburn  8692:         return(1,$currentphase);
1.582     raeburn  8693:     }
1.691     raeburn  8694: 
1.157     albertel 8695:     if (!$max_bubble) { $max_bubble=2**31; }
                   8696:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8697: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8698: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8699: 	my $scan_record =
                   8700:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8701: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8702:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8703:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8704: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8705: 	my @to_correct;
1.470     foxr     8706: 	
                   8707: 	# Probably here's where the error is...
                   8708: 
1.157     albertel 8709: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8710:             my $lastbubble;
                   8711:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8712:                my $question = $1;
                   8713:                my $subquestion = $2;
1.691     raeburn  8714:                my ($first,$responsenum);
                   8715:                if ($randomorder || $randompick) {
                   8716:                    $responsenum = $respnumlookup{$question-1};
                   8717:                    $first = $startline{$question-1};
                   8718:                } else {
                   8719:                    $responsenum = $question-1; 
                   8720:                    $first = $first_bubble_line{$responsenum};
                   8721:                }
                   8722:                if (!defined($first)) { next; }
                   8723:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8724:                my $subcount = 1;
                   8725:                while ($subcount<$subquestion) {
                   8726:                    $first += $subans[$subcount-1];
                   8727:                    $subcount ++;
                   8728:                }
                   8729:                my $count = $subans[$subquestion-1];
                   8730:                $lastbubble = $first + $count;
                   8731:             } else {
1.691     raeburn  8732:                my ($first,$responsenum);
                   8733:                if ($randomorder || $randompick) {
                   8734:                    $responsenum = $respnumlookup{$missing-1};
                   8735:                    $first = $startline{$missing-1};
                   8736:                } else {
                   8737:                    $responsenum = $missing-1;
                   8738:                    $first = $first_bubble_line{$responsenum};
                   8739:                }
                   8740:                if (!defined($first)) { next; }
                   8741:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8742:             }
                   8743:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8744: 	    push(@to_correct,$missing);
                   8745: 	}
                   8746: 	if (@to_correct) {
                   8747: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8748: 				     $line,'missingbubble',\@to_correct,
                   8749:                                      $randomorder,$randompick,\%respnumlookup,
                   8750:                                      \%startline);
1.157     albertel 8751: 	    return (1,$currentphase);
                   8752: 	}
                   8753: 
                   8754:     }
                   8755:     return (0,$currentphase+1);
                   8756: }
                   8757: 
1.663     raeburn  8758: sub hand_bubble_option {
                   8759:     my (undef, undef, $sequence) =
                   8760:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8761:     return if ($sequence eq '');
                   8762:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8763:     unless (ref($navmap)) {
                   8764:         return;
                   8765:     }
                   8766:     my $needs_hand_bubbles;
                   8767:     my $map=$navmap->getResourceByUrl($sequence);
                   8768:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8769:     foreach my $res (@resources) {
                   8770:         if (ref($res)) {
                   8771:             if ($res->is_problem()) {
                   8772:                 my $partlist = $res->parts();
                   8773:                 foreach my $part (@{ $partlist }) {
                   8774:                     my @types = $res->responseType($part);
                   8775:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8776:                         $needs_hand_bubbles = 1;
                   8777:                         last;
                   8778:                     }
                   8779:                 }
                   8780:             }
                   8781:         }
                   8782:     }
                   8783:     if ($needs_hand_bubbles) {
1.754     raeburn  8784:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  8785:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8786:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8787:                &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 />').
                   8788:                '<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  8789:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8790:     }
                   8791:     return;
                   8792: }
1.423     albertel 8793: 
1.82      albertel 8794: sub scantron_process_students {
1.608     www      8795:     my ($r,$symb) = @_;
1.513     foxr     8796: 
1.257     albertel 8797:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8798:     if (!$symb) {
                   8799: 	return '';
                   8800:     }
1.324     albertel 8801:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8802: 
1.754     raeburn  8803:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8804:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8805:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8806:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8807:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8808:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8809:     unless (ref($navmap)) {
                   8810:         $r->print(&navmap_errormsg());
                   8811:         return '';
1.691     raeburn  8812:     }
1.83      albertel 8813:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8814:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8815:         %grader_randomlists_by_symb);
1.677     raeburn  8816:     if (ref($map)) {
                   8817:         $randomorder = $map->randomorder();
1.689     raeburn  8818:         $randompick = $map->randompick();
1.691     raeburn  8819:     } else {
                   8820:         $r->print(&navmap_errormsg());
                   8821:         return '';
1.677     raeburn  8822:     }
1.691     raeburn  8823:     my $nav_error;
1.83      albertel 8824:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8825:     if ($randomorder || $randompick) {
                   8826:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8827:         if ($nav_error) {
                   8828:             $r->print(&navmap_errormsg());
                   8829:             return '';
                   8830:         }
                   8831:     }
1.557     raeburn  8832:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8833:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8834: 
1.554     raeburn  8835:     my ($uname,$udom);
1.82      albertel 8836:     my $result= <<SCANTRONFORM;
1.81      albertel 8837: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8838:   <input type="hidden" name="command" value="scantron_configphase" />
                   8839:   $default_form_data
                   8840: SCANTRONFORM
1.82      albertel 8841:     $r->print($result);
                   8842: 
1.770     raeburn  8843:     my ($checksec,@possibles)=&gradable_sections();
1.82      albertel 8844:     my @delayqueue;
1.542     raeburn  8845:     my (%completedstudents,%scandata);
1.770     raeburn  8846: 
1.520     www      8847:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8848:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8849:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8850:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8851:     $r->print('<br />');
1.140     albertel 8852:     my $start=&Time::HiRes::time();
1.158     albertel 8853:     my $i=-1;
1.542     raeburn  8854:     my $started;
1.447     foxr     8855: 
1.649     raeburn  8856:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8857:     if ($nav_error) {
                   8858:         $r->print(&navmap_errormsg());
                   8859:         return '';
                   8860:     }
                   8861: 
1.513     foxr     8862:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8863:     # the user and return.
                   8864: 
                   8865:     if ($ssi_error) {
                   8866: 	$r->print("</form>");
                   8867: 	&ssi_print_error($r);
1.520     www      8868:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8869: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8870:     }
1.447     foxr     8871: 
1.755     raeburn  8872:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8873:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8874:     my %orderedforcode;
1.542     raeburn  8875: 
1.157     albertel 8876:     while ($i<$scanlines->{'count'}) {
                   8877:  	($uname,$udom)=('','');
                   8878:  	$i++;
1.200     albertel 8879:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8880:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8881: 	if ($started) {
1.667     www      8882: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8883: 	}
                   8884: 	$started=1;
1.691     raeburn  8885:         my %respnumlookup = ();
                   8886:         my %startline = ();
                   8887:         my $total;
1.157     albertel 8888:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8889:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8890:                                                  $randompick,$sequence,\@master_seq,
                   8891:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8892:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8893:                                                  \$total);
1.157     albertel 8894:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8895:  					      \%idmap,$i)) {
                   8896:   	    &scantron_add_delay(\@delayqueue,$line,
                   8897:  				'Unable to find a student that matches',1);
                   8898:  	    next;
                   8899:   	}
                   8900:  	if (exists $completedstudents{$uname}) {
                   8901:  	    &scantron_add_delay(\@delayqueue,$line,
                   8902:  				'Student '.$uname.' has multiple sheets',2);
                   8903:  	    next;
                   8904:  	}
1.677     raeburn  8905:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
1.770     raeburn  8906:         if (($checksec ne '') && ($checksec ne $usec)) {
                   8907:             unless (grep(/^\Q$usec\E$/,@possibles)) {
                   8908:                 &scantron_add_delay(\@delayqueue,$line,
                   8909:                                     "No role with manage grades privilege in student's section ($usec)",3);
                   8910:                 next;
                   8911:             }
                   8912:         }
1.677     raeburn  8913:         my $user = $uname.':'.$usec;
1.157     albertel 8914:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8915: 
1.677     raeburn  8916:         my $scancode;
                   8917:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8918:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8919:             $scancode = $scan_record->{'scantron.CODE'};
                   8920:         } else {
                   8921:             $scancode = '';
                   8922:         }
                   8923: 
                   8924:         my @mapresources = @resources;
1.689     raeburn  8925:         if ($randomorder || $randompick) {
1.678     raeburn  8926:             @mapresources = 
1.691     raeburn  8927:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8928:                              \%orderedforcode);
1.677     raeburn  8929:         }
1.586     raeburn  8930:         my (%partids_by_symb,$res_error);
1.677     raeburn  8931:         foreach my $resource (@mapresources) {
1.586     raeburn  8932:             my $ressymb;
                   8933:             if (ref($resource)) {
                   8934:                 $ressymb = $resource->symb();
                   8935:             } else {
                   8936:                 $res_error = 1;
                   8937:                 last;
                   8938:             }
1.557     raeburn  8939:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8940:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  8941:                 my $currcode;
                   8942:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8943:                     $currcode = $scancode;
                   8944:                 }
1.557     raeburn  8945:                 my ($analysis,$parts) =
1.672     raeburn  8946:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  8947:                                               $uname,$udom,undef,$bubbles_per_row,
                   8948:                                               $currcode);
1.557     raeburn  8949:                 $partids_by_symb{$ressymb} = $parts;
                   8950:             } else {
                   8951:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8952:             }
1.554     raeburn  8953:         }
                   8954: 
1.586     raeburn  8955:         if ($res_error) {
                   8956:             &scantron_add_delay(\@delayqueue,$line,
                   8957:                                 'An error occurred while grading student '.$uname,2);
                   8958:             next;
                   8959:         }
                   8960: 
1.330     albertel 8961: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8962:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8963: 
                   8964: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8965: 	    &scantron_putfile($scanlines,$scan_data);
                   8966: 	}
1.161     albertel 8967: 	
1.542     raeburn  8968:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8969:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8970:                                    $bubbles_per_row,$randomorder,$randompick,
                   8971:                                    \%respnumlookup,\%startline) 
                   8972:             eq 'ssi_error') {
1.542     raeburn  8973:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8974:             $r->print("</form>");
                   8975:             &ssi_print_error($r);
                   8976:             &Apache::lonnet::remove_lock($lock);
                   8977:             return '';      # Why return ''?  Beats me.
                   8978:         }
1.513     foxr     8979: 
1.692     raeburn  8980:         if (($scancode) && ($randomorder || $randompick)) {
                   8981:             my $parmresult =
                   8982:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8983:                                                        '0_examcode',2,$scancode,
                   8984:                                                        'string_examcode',$uname,
                   8985:                                                        $udom);
                   8986:         }
1.140     albertel 8987: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8988:         if ($env{'form.verifyrecord'}) {
                   8989:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8990:             if ($randompick) {
                   8991:                 if ($total) {
                   8992:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8993:                 }
                   8994:             }
                   8995: 
1.542     raeburn  8996:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8997:             chomp($studentdata);
                   8998:             $studentdata =~ s/\r$//;
                   8999:             my $studentrecord = '';
                   9000:             my $counter = -1;
1.677     raeburn  9001:             foreach my $resource (@mapresources) {
1.554     raeburn  9002:                 my $ressymb = $resource->symb();
1.542     raeburn  9003:                 ($counter,my $recording) =
                   9004:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9005:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9006:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   9007:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  9008:                 $studentrecord .= $recording;
                   9009:             }
                   9010:             if ($studentrecord ne $studentdata) {
1.554     raeburn  9011:                 &Apache::lonxml::clear_problem_counter();
                   9012:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  9013:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  9014:                                            $bubbles_per_row,$randomorder,$randompick,
                   9015:                                            \%respnumlookup,\%startline) 
                   9016:                     eq 'ssi_error') {
1.554     raeburn  9017:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   9018:                     $r->print("</form>");
                   9019:                     &ssi_print_error($r);
                   9020:                     &Apache::lonnet::remove_lock($lock);
                   9021:                     delete($completedstudents{$uname});
                   9022:                     return '';
                   9023:                 }
1.542     raeburn  9024:                 $counter = -1;
                   9025:                 $studentrecord = '';
1.677     raeburn  9026:                 foreach my $resource (@mapresources) {
1.554     raeburn  9027:                     my $ressymb = $resource->symb();
1.542     raeburn  9028:                     ($counter,my $recording) =
                   9029:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  9030:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  9031:                                                  \%scantron_config,\%lettdig,$numletts,
                   9032:                                                  $randomorder,$randompick,\%respnumlookup,
                   9033:                                                  \%startline);
1.542     raeburn  9034:                     $studentrecord .= $recording;
                   9035:                 }
                   9036:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   9037:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  9038:                     if ($scancode eq '') {
1.658     bisitz   9039:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  9040:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   9041:                     } else {
1.658     bisitz   9042:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  9043:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   9044:                     }
                   9045:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   9046:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   9047:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   9048:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   9049:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9050:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   9051:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  9052:                               &Apache::loncommon::end_data_table_row().
                   9053:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   9054:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   9055:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  9056:                               &Apache::loncommon::end_data_table_row().
                   9057:                               &Apache::loncommon::end_data_table().'</p>');
                   9058:                 } else {
                   9059:                     $r->print('<br /><span class="LC_warning">'.
                   9060:                              &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 />'.
                   9061:                              &mt("As a consequence, this user's submission history records two tries.").
                   9062:                                  '</span><br />');
                   9063:                 }
                   9064:             }
                   9065:         }
1.543     raeburn  9066:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 9067:     } continue {
1.330     albertel 9068: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  9069: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 9070:     }
1.140     albertel 9071:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      9072:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 9073: #    my $lasttime = &Time::HiRes::time()-$start;
                   9074: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 9075: 
1.200     albertel 9076:     $r->print("</form>");
1.157     albertel 9077:     return '';
1.75      albertel 9078: }
1.157     albertel 9079: 
1.557     raeburn  9080: sub graders_resources_pass {
1.649     raeburn  9081:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   9082:         $bubbles_per_row) = @_;
1.557     raeburn  9083:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   9084:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   9085:         foreach my $resource (@{$resources}) {
                   9086:             my $ressymb = $resource->symb();
                   9087:             my ($analysis,$parts) =
                   9088:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  9089:                                           $env{'user.name'},$env{'user.domain'},
                   9090:                                           1,$bubbles_per_row);
1.557     raeburn  9091:             $grader_partids_by_symb->{$ressymb} = $parts;
                   9092:             if (ref($analysis) eq 'HASH') {
                   9093:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   9094:                     $grader_randomlists_by_symb->{$ressymb} =
                   9095:                         $analysis->{'parts_withrandomlist'};
                   9096:                 }
                   9097:             }
                   9098:         }
                   9099:     }
                   9100:     return;
                   9101: }
                   9102: 
1.678     raeburn  9103: =pod
                   9104: 
                   9105: =item users_order
                   9106: 
                   9107:   Returns array of resources in current map, ordered based on either CODE,
                   9108:   if this is a CODEd exam, or based on student's identity if this is a 
                   9109:   "NAMEd" exam.
                   9110: 
1.691     raeburn  9111:   Should be used when randomorder and/or randompick applied when the 
                   9112:   corresponding exam was printed, prior to students completing bubblesheets 
                   9113:   for the version of the exam the student received.
1.678     raeburn  9114: 
                   9115: =cut
                   9116: 
                   9117: sub users_order  {
1.691     raeburn  9118:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  9119:     my @mapresources;
1.691     raeburn  9120:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  9121:         return @mapresources;
1.691     raeburn  9122:     }
                   9123:     if ($scancode) {
                   9124:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   9125:             @mapresources = @{$orderedforcode->{$scancode}};
                   9126:         } else {
                   9127:             $env{'form.CODE'} = $scancode;
                   9128:             my $actual_seq =
                   9129:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9130:                                                                $master_seq,
                   9131:                                                                $user,$scancode,1);
                   9132:             if (ref($actual_seq) eq 'ARRAY') {
                   9133:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9134:                 if (ref($orderedforcode) eq 'HASH') {
                   9135:                     if (@mapresources > 0) { 
                   9136:                         $orderedforcode->{$scancode} = \@mapresources;
                   9137:                     }
                   9138:                 }
                   9139:             }
                   9140:             delete($env{'form.CODE'});
1.678     raeburn  9141:         }
                   9142:     } else {
                   9143:         my $actual_seq =
                   9144:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   9145:                                                            $master_seq,
1.688     raeburn  9146:                                                            $user,undef,1);
1.678     raeburn  9147:         if (ref($actual_seq) eq 'ARRAY') {
                   9148:             @mapresources = 
                   9149:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   9150:         }
1.691     raeburn  9151:     }
                   9152:     return @mapresources;
1.678     raeburn  9153: }
                   9154: 
1.542     raeburn  9155: sub grade_student_bubbles {
1.691     raeburn  9156:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9157:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9158:     my $uselookup = 0;
                   9159:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9160:         (ref($startline) eq 'HASH')) {
                   9161:         $uselookup = 1;
                   9162:     }
                   9163: 
1.554     raeburn  9164:     if (ref($resources) eq 'ARRAY') {
                   9165:         my $count = 0;
                   9166:         foreach my $resource (@{$resources}) {
                   9167:             my $ressymb = $resource->symb();
                   9168:             my %form = ('submitted'      => 'scantron',
                   9169:                         'grade_target'   => 'grade',
                   9170:                         'grade_username' => $uname,
                   9171:                         'grade_domain'   => $udom,
                   9172:                         'grade_courseid' => $env{'request.course.id'},
                   9173:                         'grade_symb'     => $ressymb,
                   9174:                         'CODE'           => $scancode
                   9175:                        );
1.649     raeburn  9176:             if ($bubbles_per_row ne '') {
                   9177:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9178:             }
1.663     raeburn  9179:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9180:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9181:             }
1.554     raeburn  9182:             if (ref($parts) eq 'HASH') {
                   9183:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9184:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  9185:                         if ($uselookup) {
                   9186:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9187:                         } else {
                   9188:                             $form{'scantron_questnum_start.'.$part} =
                   9189:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9190:                         }
1.554     raeburn  9191:                         $count++;
                   9192:                     }
                   9193:                 }
                   9194:             }
                   9195:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9196:             return 'ssi_error' if ($ssi_error);
                   9197:             last if (&Apache::loncommon::connection_aborted($r));
                   9198:         }
1.542     raeburn  9199:     }
                   9200:     return;
                   9201: }
                   9202: 
1.157     albertel 9203: sub scantron_upload_scantron_data {
1.767     raeburn  9204:     my ($r,$symb) = @_;
1.565     raeburn  9205:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9206:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9207:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9208:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9209:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9210: 							  'domainid',
1.565     raeburn  9211: 							  'coursename',$dom);
                   9212:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9213:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9214:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9215:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9216:     &js_escape(\$nofile_alert);
1.579     raeburn  9217:     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  9218:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9219:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9220:     function checkUpload(formname) {
                   9221: 	if (formname.upfile.value == "") {
1.579     raeburn  9222: 	    alert("'.$nofile_alert.'");
1.157     albertel 9223: 	    return false;
                   9224: 	}
1.565     raeburn  9225:         if (formname.courseid.value == "") {
1.579     raeburn  9226:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9227:             return false;
                   9228:         }
1.157     albertel 9229: 	formname.submit();
                   9230:     }
1.565     raeburn  9231: 
                   9232:     function ToSyllabus() {
                   9233:         var cdom = '."'$dom'".';
                   9234:         var cnum = document.rules.courseid.value;
                   9235:         if (cdom == "" || cdom == null) {
                   9236:             return;
                   9237:         }
                   9238:         if (cnum == "" || cnum == null) {
                   9239:            return;
                   9240:         }
                   9241:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9242:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9243:         return;
                   9244:     }
                   9245: 
1.754     raeburn  9246:     '.$formatjs.'
1.597     wenzelju 9247: '));
                   9248:     $r->print('
1.648     bisitz   9249: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9250: 
1.492     albertel 9251: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9252: '.$default_form_data.
                   9253:   &Apache::lonhtmlcommon::start_pick_box().
                   9254:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9255:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9256:   &Apache::lonhtmlcommon::row_closure().
                   9257:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9258:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9259:   &Apache::lonhtmlcommon::row_closure().
                   9260:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9261:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9262:   &Apache::lonhtmlcommon::row_closure());
                   9263:     if ($formatoptions) {
                   9264:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9265:                   &Apache::lonhtmlcommon::row_closure());
                   9266:     }
                   9267:     $r->print(
1.565     raeburn  9268:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9269:   '<input type="file" name="upfile" size="50" />'.
                   9270:   &Apache::lonhtmlcommon::row_closure(1).
                   9271:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9272: 
1.492     albertel 9273: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9274: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9275: </form>
1.492     albertel 9276: ');
1.157     albertel 9277:     return '';
                   9278: }
                   9279: 
1.754     raeburn  9280: sub scantron_upload_dataformat {
                   9281:     my ($dom) = @_;
                   9282:     my ($formatoptions,$formattitle,$formatjs);
                   9283:     $formatjs = <<'END';
                   9284: function toggleScantab(form) {
                   9285:    return;
                   9286: }
                   9287: END
                   9288:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9289:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9290:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9291:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9292:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9293:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9294:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9295:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9296:                             my ($onclick,$formatextra,$singleline);
                   9297:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9298:                             my $count = 0;
                   9299:                             foreach my $line (@lines) {
                   9300:                                 next if ($line =~ /^#/);
                   9301:                                 $singleline = $line;
                   9302:                                 $count ++;
                   9303:                             }
                   9304:                             if ($count > 1) {
                   9305:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9306:                                                '<span class="LC_nobreak">'.
                   9307:                                                &mt('Bubblesheet type:').'&nbsp;'.
                   9308:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9309:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9310:                                 $formatjs = <<"END";
1.754     raeburn  9311: function toggleScantab(form) {
                   9312:     var divid = 'bubbletype';
                   9313:     if (document.getElementById(divid)) {
                   9314:         var radioname = 'fileformat';
                   9315:         var num = form.elements[radioname].length;
                   9316:         if (num) {
                   9317:             for (var i=0; i<num; i++) {
                   9318:                 if (form.elements[radioname][i].checked) {
                   9319:                     var chosen = form.elements[radioname][i].value;
                   9320:                     if (chosen == 'dat') {
                   9321:                         document.getElementById(divid).style.display = 'none';
                   9322:                     } else if (chosen == 'csv') {
1.757     raeburn  9323:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9324:                     }
                   9325:                 }
                   9326:             }
                   9327:         }
                   9328:     }
                   9329:     return;
                   9330: }
                   9331: 
                   9332: END
1.756     raeburn  9333:                             } elsif ($count == 1) {
                   9334:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9335:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9336:                             }
                   9337:                             $formattitle = &mt('File format');
                   9338:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9339:                                              &mt('Plain Text (no delimiters)').
                   9340:                                              '</label>'.('&nbsp;'x2).
                   9341:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9342:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9343:                         }
                   9344:                     }
                   9345:                 }
                   9346:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9347:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9348:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9349:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9350:                         $formatoptions = &scantron_scantab();
                   9351:                     }
1.754     raeburn  9352:                 }
                   9353:             }
                   9354:         }
                   9355:     }
                   9356:     return ($formatoptions,$formattitle,$formatjs);
                   9357: }
1.423     albertel 9358: 
1.157     albertel 9359: sub scantron_upload_scantron_data_save {
1.767     raeburn  9360:     my ($r,$symb) = @_;
1.182     albertel 9361:     my $doanotherupload=
                   9362: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9363: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9364: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9365: 	'</form>'."\n";
1.257     albertel 9366:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9367: 	!&Apache::lonnet::allowed('usc',
1.770     raeburn  9368: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'}) &&
                   9369:         !&Apache::lonnet::allowed('usc',
                   9370:                             $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
1.575     www      9371: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9372: 	unless ($symb) {
1.182     albertel 9373: 	    $r->print($doanotherupload);
                   9374: 	}
1.162     albertel 9375: 	return '';
                   9376:     }
1.257     albertel 9377:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9378:     my $uploadedfile;
1.710     bisitz   9379:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9380:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9381:         $r->print(
                   9382:             &Apache::lonhtmlcommon::confirm_success(
                   9383:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9384:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9385:     } else {
1.754     raeburn  9386:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9387:         my $parser;
                   9388:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9389:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9390:                 my $is_csv;
                   9391:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9392:                 if (@possibles > 1) {
                   9393:                     if ($env{'form.fileformat'} eq 'csv') {
                   9394:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9395:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9396:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9397:                                     $is_csv = 1;
                   9398:                                 }
1.754     raeburn  9399:                             }
                   9400:                         }
                   9401:                     }
                   9402:                 } elsif (@possibles == 1) {
                   9403:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9404:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9405:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9406:                                 $is_csv = 1;
                   9407:                             }
1.754     raeburn  9408:                         }
                   9409:                     }
                   9410:                 }
                   9411:                 if ($is_csv) {
                   9412:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9413:                 }
                   9414:             }
                   9415:         }
                   9416:         my $result =
                   9417:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9418:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9419:         if ($result =~ m{^/uploaded/}) {
                   9420:             $r->print(
                   9421:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9422:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9423:                         (length($env{'form.upfile'})-1),
                   9424:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9425:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.770     raeburn  9426:             if ($uploadedfile =~ /^scantron_orig_/) {
                   9427:                 my $logname = $uploadedfile;
                   9428:                 $logname =~ s/^scantron_orig_//;
                   9429:                 if ($logname ne '') {
                   9430:                     my $now = time;
                   9431:                     my %info = ($logname => { $now => $env{'user.name'}.':'.$env{'user.domain'} });  
                   9432:                     &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9433:                 }
                   9434:             }
1.567     raeburn  9435:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.770     raeburn  9436:                                                        $env{'form.courseid'},$symb,$uploadedfile));
1.710     bisitz   9437:         } else {
                   9438:             $r->print(
                   9439:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9440:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9441:                           $result,
1.568     raeburn  9442: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9443: 	}
                   9444:     }
1.174     albertel 9445:     if ($symb) {
1.612     www      9446: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9447:     } else {
1.182     albertel 9448: 	$r->print($doanotherupload);
1.174     albertel 9449:     }
1.157     albertel 9450:     return '';
                   9451: }
                   9452: 
1.567     raeburn  9453: sub validate_uploaded_scantron_file {
1.770     raeburn  9454:     my ($cdom,$cname,$symb,$fname,$context,$countsref) = @_;
                   9455: 
1.567     raeburn  9456:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9457:     my @lines;
                   9458:     if ($scanlines ne '-1') {
                   9459:         @lines=split("\n",$scanlines,-1);
                   9460:     }
1.770     raeburn  9461:     my ($output,$secidx,$checksec,$priv,%crsroleshash,@possibles);
                   9462:     $secidx = &Apache::loncoursedata::CL_SECTION();
                   9463:     if ($context eq 'download') {
                   9464:         $priv = 'mgr';
                   9465:     } else {
                   9466:         $priv = 'usc';
                   9467:     }
                   9468:     unless ((&Apache::lonnet::allowed($priv,$env{'request.role.domain'})) ||
                   9469:             (($env{'request.course.id'}) &&
                   9470:              (&Apache::lonnet::allowed($priv,$env{'request.course.id'})))) {
                   9471:         if ($env{'request.course.sec'} ne '') {
                   9472:             unless (&Apache::lonnet::allowed($priv,
                   9473:                                          "$env{'request.course.id'}/$env{'request.course.sec'}")) {
                   9474:                 unless ($context eq 'download') {
                   9475:                     $output = '<p class="LC_warning">'.&mt('You do not have permission to upload bubblesheet data').'</p>';
                   9476:                 }
                   9477:                 return $output;
                   9478:             }
                   9479:             ($checksec,@possibles)=&gradable_sections();
                   9480:         }
                   9481:     }
1.567     raeburn  9482:     if (@lines) {
                   9483:         my (%counts,$max_match_format);
1.710     bisitz   9484:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9485:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9486:         my %idmap = &username_to_idmap($classlist);
                   9487:         foreach my $key (keys(%idmap)) {
                   9488:             my $lckey = lc($key);
                   9489:             $idmap{$lckey} = $idmap{$key};
                   9490:         }
                   9491:         my %unique_formats;
1.754     raeburn  9492:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9493:         foreach my $line (@formatlines) {
                   9494:             chomp($line);
                   9495:             my @config = split(/:/,$line);
                   9496:             my $idstart = $config[5];
                   9497:             my $idlength = $config[6];
                   9498:             if (($idstart ne '') && ($idlength > 0)) {
                   9499:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9500:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9501:                 } else {
                   9502:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9503:                 }
                   9504:             }
                   9505:         }
                   9506:         foreach my $key (keys(%unique_formats)) {
                   9507:             my ($idstart,$idlength) = split(':',$key);
                   9508:             %{$counts{$key}} = (
                   9509:                                'found'   => 0,
                   9510:                                'total'   => 0,
1.770     raeburn  9511:                                'totalanysec' => 0,
                   9512:                                'othersec' => 0,
1.567     raeburn  9513:                               );
                   9514:             foreach my $line (@lines) {
                   9515:                 next if ($line =~ /^#/);
                   9516:                 next if ($line =~ /^[\s\cz]*$/);
                   9517:                 my $id = substr($line,$idstart-1,$idlength);
                   9518:                 $id = lc($id);
                   9519:                 if (exists($idmap{$id})) {
1.770     raeburn  9520:                     if ($checksec ne '') {
                   9521:                         $counts{$key}{'totalanysec'} ++;
                   9522:                         if (ref($classlist->{$idmap{$id}}) eq 'ARRAY') {
                   9523:                             my $stusec = $classlist->{$idmap{$id}}->[$secidx];
                   9524:                             if ($stusec ne $checksec) {
                   9525:                                 if (@possibles) {
                   9526:                                     unless (grep(/^\Q$stusec\E$/,@possibles)) {
                   9527:                                         $counts{$key}{'othersec'} ++;
                   9528:                                         next;
                   9529:                                     }
                   9530:                                 } else {
                   9531:                                     $counts{$key}{'othersec'} ++;
                   9532:                                     next;
                   9533:                                 }
                   9534:                             }
                   9535:                         }
                   9536:                     }
1.567     raeburn  9537:                     $counts{$key}{'found'} ++;
                   9538:                 }
                   9539:                 $counts{$key}{'total'} ++;
                   9540:             }
                   9541:             if ($counts{$key}{'total'}) {
                   9542:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9543:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9544:                     $max_match_pct = $percent_match;
                   9545:                     $max_match_format = $key;
1.710     bisitz   9546:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9547:                     $max_match_count = $counts{$key}{'total'};
                   9548:                 }
                   9549:             }
                   9550:         }
1.770     raeburn  9551:         if ((ref($unique_formats{$max_match_format}) eq 'ARRAY') && ($context ne 'download')) {
1.567     raeburn  9552:             my $format_descs;
                   9553:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9554:             for (my $i=0; $i<$numwithformat; $i++) {
                   9555:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9556:                 if ($i<$numwithformat-2) {
                   9557:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9558:                 } elsif ($i==$numwithformat-2) {
                   9559:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9560:                 } elsif ($i==$numwithformat-1) {
                   9561:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9562:                 }
                   9563:             }
                   9564:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9565:             $output .= '<br />';
                   9566:             if ($found_match_count == $max_match_count) {
                   9567:                 # 100% matching entries
                   9568:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9569:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9570:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9571:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9572:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9573:                     ' in the file (for the format defined for [_3]).',
                   9574:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9575:             } else {
                   9576:                 # Not all entries matching? -> Show warning and additional info
                   9577:                 $output .=
                   9578:                     &Apache::lonhtmlcommon::confirm_success(
                   9579:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9580:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9581:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9582:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9583:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9584:                         ' in the file (for the format defined for [_3]).',
                   9585:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9586:                     '<p class="LC_info">'.
                   9587:                     &mt('A low percentage of matches results from one of the following:').
                   9588:                     '</p><ul>'.
                   9589:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9590:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9591:                                '<i>'.$cdom.'</i>').'</li>'.
                   9592:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9593:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9594:                     '</ul>';
                   9595:             }
1.770     raeburn  9596:             if (($checksec ne '') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9597:                 if ($counts{$max_match_format}{'othersec'}) {
                   9598:                     my $percent_nongrade = (100*$counts{$max_match_format}{'othersec'})/($counts{$max_match_format}{'totalanysec'});
                   9599:                     my $showpct = sprintf("%.0f",$percent_nongrade).'%';
                   9600:                     my $confirmdel = &mt('Are you sure you want to permanently delete this file?');
                   9601:                     &js_escape(\$confirmdel);
                   9602:                     $output .= '<p class="LC_warning">'.
                   9603:                                &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',
                   9604:                                    '<b>',$counts{$max_match_format}{'othersec'},'</b>').
                   9605:                                '<br />'.
                   9606:                                &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>').
                   9607:                                '</p><p>'.
                   9608:                                &mt('If you prefer to delete the file now, use: [_1]').
                   9609:                                '<form method="post" name="delupload" action="/adm/grades">'.
                   9610:                                '<input type="hidden" name="symb" value="'.$symb.'" />'.
                   9611:                                '<input type="hidden" name="domainid" value="'.$cdom.'" />'.
                   9612:                                '<input type="hidden" name="courseid" value="'.$cname.'" />'.
                   9613:                                '<input type="hidden" name="coursesec" value="'.$env{'request.course.sec'}.'" />'. 
                   9614:                                '<input type="hidden" name="uploadedfile" value="'.$fname.'" />'. 
                   9615:                                '<input type="hidden" name="command" value="scantronupload_delete" />'.
                   9616:                                '<input type="button" name="delbutton" value="'.&mt('Delete Uploaded File').'" onclick="javascript:if (confirm('."'$confirmdel'".')) { document.delupload.submit(); }" />'.
                   9617:                                '</form></p>';
                   9618:                 }
                   9619:             }
1.567     raeburn  9620:         }
1.770     raeburn  9621:         if (($context eq 'download') && ($checksec ne '')) {
                   9622:             if ((ref($countsref) eq 'HASH') && (ref($counts{$max_match_format}) eq 'HASH')) {
                   9623:                 $countsref->{'totalanysec'} = $counts{$max_match_format}{'totalanysec'};
                   9624:                 $countsref->{'othersec'} = $counts{$max_match_format}{'othersec'};
                   9625:             }
                   9626:         } 
                   9627:     } elsif ($context ne 'download') {
1.710     bisitz   9628:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9629:     }
                   9630:     return $output;
                   9631: }
                   9632: 
1.770     raeburn  9633: sub gradable_sections {
                   9634:     my $checksec = $env{'request.course.sec'};
                   9635:     my @oksecs;
                   9636:     if ($checksec) {
                   9637:         my %availablesecs = &sections_grade_privs();
                   9638:         if (ref($availablesecs{'mgr'}) eq 'ARRAY') {
                   9639:             foreach my $sec (@{$availablesecs{'mgr'}}) {
                   9640:                 unless (grep(/^\Q$sec\E$/,@oksecs)) {
                   9641:                     push(@oksecs,$sec);
                   9642:                 }
                   9643:             }
                   9644:             if (grep(/^all$/,@oksecs)) {
                   9645:                 undef($checksec);
                   9646:             }
                   9647:         }
                   9648:     }
                   9649:     return($checksec,@oksecs);
                   9650: }
                   9651: 
                   9652: sub sections_grade_privs {
                   9653:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9654:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9655:     my %availablesecs = (
                   9656:                           mgr => [],
                   9657:                           vgr => [],
                   9658:                           usc => [],
                   9659:                         );
                   9660:     my $ccrole = 'cc';
                   9661:     if ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Community') {
                   9662:         $ccrole = 'co';
                   9663:     }
                   9664:     my %crsroleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
                   9665:                                                      'userroles',['active'],
                   9666:                                                      [$ccrole,'in','cr'],$cdom,1);
                   9667:     my $crsid = $cnum.':'.$cdom;
                   9668:     foreach my $item (keys(%crsroleshash)) {
                   9669:         next unless ($item =~ /^$crsid\:/);
                   9670:         my ($crsnum,$crsdom,$role,$sec) = split(/\:/,$item);
                   9671:         my $suffix = "/$cdom/$cnum./$cdom/$cnum";
                   9672:         if ($sec ne '') {
                   9673:             $suffix = "/$cdom/$cnum/$sec./$cdom/$cnum/$sec";
                   9674:         }
                   9675:         if (($role eq $ccrole) || ($role eq 'in')) {
                   9676:             foreach my $priv ('mgr','vgr','usc') { 
                   9677:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9678:                     if ($sec eq '') {
                   9679:                         $availablesecs{$priv} = ['all'];
                   9680:                     } elsif ($sec ne $env{'request.course.sec'}) {
                   9681:                         unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9682:                             push(@{$availablesecs{$priv}},$sec);
                   9683:                         }
                   9684:                     }
                   9685:                 }
                   9686:             }
                   9687:         } elsif ($role =~ m{^cr/}) {
                   9688:             foreach my $priv ('mgr','vgr','usc') {
                   9689:                 unless (grep(/^all$/,@{$availablesecs{$priv}})) {
                   9690:                     if ($env{"user.priv.$role.$suffix"} =~ /:$priv&/) {
                   9691:                         if ($sec eq '') {
                   9692:                             $availablesecs{$priv} = ['all'];
                   9693:                         } elsif ($sec ne $env{'request.course.sec'}) {
                   9694:                             unless (grep(/^\Q$sec\E$/,@{$availablesecs{$priv}})) {
                   9695:                                 push(@{$availablesecs{$priv}},$sec);
                   9696:                             }
                   9697:                         }
                   9698:                     }
                   9699:                 }
                   9700:             }
                   9701:         }
                   9702:     }
                   9703:     return %availablesecs;
                   9704: }
                   9705: 
                   9706: sub scantron_upload_delete {
                   9707:     my ($r,$symb) = @_;
                   9708:     my $filename = $env{'form.uploadedfile'};
                   9709:     if ($filename =~ /^scantron_orig_/) {
                   9710:         if (&Apache::lonnet::allowed('usc',$env{'form.domainid'}) ||
                   9711:             &Apache::lonnet::allowed('usc',
                   9712:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}) ||
                   9713:             &Apache::lonnet::allowed('usc',
                   9714:                                      $env{'form.domainid'}.'_'.$env{'form.courseid'}.'/'.$env{'form.coursesec'})) {
                   9715:             my $uploadurl = '/uploaded/'.$env{'form.domainid'}.'/'.$env{'form.courseid'}.'/'.$env{'form.uploadedfile'};
                   9716:             my $retrieval = &Apache::lonnet::getfile($uploadurl);
                   9717:             if ($retrieval eq '-1') {
                   9718:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9719:                           &mt('File requested for deletion not found.'));
                   9720:             } else {
                   9721:                 $filename =~ s/^scantron_orig_//;
                   9722:                 if ($filename ne '') {
                   9723:                     my ($is_valid,$numleft);
                   9724:                     my %info = &Apache::lonnet::get('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9725:                     if (keys(%info)) {
                   9726:                         if (ref($info{$filename}) eq 'HASH') {
                   9727:                             foreach my $timestamp (sort(keys(%{$info{$filename}}))) {
                   9728:                                 if ($info{$filename}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9729:                                     $is_valid = 1;
                   9730:                                     delete($info{$filename}{$timestamp}); 
                   9731:                                 }
                   9732:                             }
                   9733:                             $numleft = scalar(keys(%{$info{$filename}}));
                   9734:                         }
                   9735:                     }
                   9736:                     if ($is_valid) {
                   9737:                         my $result = &Apache::lonnet::removeuploadedurl($uploadurl);
                   9738:                         if ($result eq 'ok') {
                   9739:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion successful')).'<br />');
                   9740:                             if ($numleft) {
                   9741:                                 &Apache::lonnet::put('scantronupload',\%info,$env{'form.domainid'},$env{'form.courseid'});
                   9742:                             } else {
                   9743:                                 &Apache::lonnet::del('scantronupload',[$filename],$env{'form.domainid'},$env{'form.courseid'});
                   9744:                             }
                   9745:                         } else {
                   9746:                             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9747:                                       &mt('Result was [_1]',$result));
                   9748:                         }
                   9749:                     } else {
                   9750:                         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9751:                                   &mt('File requested for deletion was uploaded by a different user.'));
                   9752:                     }
                   9753:                 } else {
                   9754:                     $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9755:                               &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9756:                 }
                   9757:             }
                   9758:         } else {
                   9759:             $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'. 
                   9760:                       &mt('You are not permitted to delete bubblesheet data files from the requested course.'));
                   9761:         }
                   9762:     } else {
                   9763:         $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('File deletion failed'),1).'<br />'.
                   9764:                           &mt('Filename of bubblesheet data file requested for deletion is invalid.'));
                   9765:     }
                   9766:     return;
                   9767: }
                   9768: 
1.202     albertel 9769: sub valid_file {
                   9770:     my ($requested_file)=@_;
                   9771:     foreach my $filename (sort(&scantron_filenames())) {
                   9772: 	if ($requested_file eq $filename) { return 1; }
                   9773:     }
                   9774:     return 0;
                   9775: }
                   9776: 
                   9777: sub scantron_download_scantron_data {
1.767     raeburn  9778:     my ($r,$symb) = @_;
1.608     www      9779:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9780:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9781:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9782:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9783:     if (! &valid_file($file)) {
1.492     albertel 9784: 	$r->print('
1.202     albertel 9785: 	<p>
1.686     bisitz   9786: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9787:         </p>
1.492     albertel 9788: ');
1.202     albertel 9789: 	return;
                   9790:     }
1.770     raeburn  9791:     my (%uploader,$is_owner,%counts,$percent);
                   9792:     my %uploader = &Apache::lonnet::get('scantronupload',[$file],$cdom,$cname);
                   9793:     if (ref($uploader{$file}) eq 'HASH') {
                   9794:         foreach my $timestamp (sort { $a <=> $b } keys(%{$uploader{$file}})) {
                   9795:             if ($uploader{$file}{$timestamp} eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   9796:                 $is_owner = 1;
                   9797:                 last;
                   9798:             }
                   9799:         }
                   9800:     }
                   9801:     unless ($is_owner) {
                   9802:         &validate_uploaded_scantron_file($cdom,$cname,$symb,'scantron_orig_'.$file,'download',\%counts);
                   9803:         if ($counts{'totalanysec'}) {
                   9804:             my $percent_othersec = (100*$counts{'othersec'})/($counts{'totalanysec'});
                   9805:             if ($percent_othersec >= 10) {
                   9806:                 my $showpct = sprintf("%.0f",$percent_othersec).'%';
                   9807:                 $r->print('<p class="LC_warning">'.
                   9808:                           &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).
                   9809:                           '</p>');
                   9810:                 return;
                   9811:             }
                   9812:         }
                   9813:     }
1.202     albertel 9814:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9815:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9816:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9817:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9818:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9819:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9820:     $r->print('
1.202     albertel 9821:     <p>
1.723     raeburn  9822: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9823: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9824:     </p>
                   9825:     <p>
1.492     albertel 9826: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9827: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9828:     </p>
                   9829:     <p>
1.492     albertel 9830: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9831: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9832:     </p>
1.492     albertel 9833: ');
1.202     albertel 9834:     return '';
                   9835: }
1.157     albertel 9836: 
1.523     raeburn  9837: sub checkscantron_results {
1.608     www      9838:     my ($r,$symb) = @_;
1.523     raeburn  9839:     if (!$symb) {return '';}
                   9840:     my $cid = $env{'request.course.id'};
1.755     raeburn  9841:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9842:     my $numletts = scalar(keys(%lettdig));
                   9843:     my $cnum = $env{'course.'.$cid.'.num'};
                   9844:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9845:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9846:     my %record;
                   9847:     my %scantron_config =
1.754     raeburn  9848:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  9849:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.770     raeburn  9850:     my ($scanlines,$scan_data)=&scantron_getfile();
1.523     raeburn  9851:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9852:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9853:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9854:     unless (ref($navmap)) {
                   9855:         $r->print(&navmap_errormsg());
                   9856:         return '';
                   9857:     }
1.523     raeburn  9858:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9859:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9860:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  9861:     if (ref($map)) { 
                   9862:         $randomorder=$map->randomorder();
1.689     raeburn  9863:         $randompick=$map->randompick();
1.677     raeburn  9864:     }
1.557     raeburn  9865:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9866:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9867:     if ($nav_error) {
                   9868:         $r->print(&navmap_errormsg());
                   9869:         return '';
1.678     raeburn  9870:     }
1.673     raeburn  9871:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9872:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9873:     my ($uname,$udom);
1.523     raeburn  9874:     my (%scandata,%lastname,%bylast);
                   9875:     $r->print('
                   9876: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9877: 
                   9878:     my @delayqueue;
                   9879:     my %completedstudents;
                   9880: 
1.691     raeburn  9881:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9882:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  9883:     my ($username,$domain,$started);
1.649     raeburn  9884:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9885:     if ($nav_error) {
                   9886:         $r->print(&navmap_errormsg());
                   9887:         return '';
                   9888:     }
1.523     raeburn  9889: 
1.667     www      9890:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  9891:     my $start=&Time::HiRes::time();
                   9892:     my $i=-1;
                   9893: 
                   9894:     while ($i<$scanlines->{'count'}) {
                   9895:         ($username,$domain,$uname)=('','','');
                   9896:         $i++;
                   9897:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9898:         if ($line=~/^[\s\cz]*$/) { next; }
                   9899:         if ($started) {
1.667     www      9900:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9901:         }
                   9902:         $started=1;
                   9903:         my $scan_record=
                   9904:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9905:                                                      $scan_data);
1.693     raeburn  9906:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9907:                                               \%idmap,$i)) {
1.523     raeburn  9908:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9909:                                 'Unable to find a student that matches',1);
                   9910:             next;
                   9911:         }
                   9912:         if (exists $completedstudents{$uname}) {
                   9913:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9914:                                 'Student '.$uname.' has multiple sheets',2);
                   9915:             next;
                   9916:         }
                   9917:         my $pid = $scan_record->{'scantron.ID'};
                   9918:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9919:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9920:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9921:         my $user = $uname.':'.$usec;
1.523     raeburn  9922:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9923: 
1.678     raeburn  9924:         my $scancode;
1.677     raeburn  9925:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9926:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9927:             $scancode = $scan_record->{'scantron.CODE'};
                   9928:         } else {
                   9929:             $scancode = '';
                   9930:         }
                   9931: 
                   9932:         my @mapresources = @resources;
1.691     raeburn  9933:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9934:         my %respnumlookup=();
                   9935:         my %startline=();
1.689     raeburn  9936:         if ($randomorder || $randompick) {
1.678     raeburn  9937:             @mapresources =
1.691     raeburn  9938:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9939:                              \%orderedforcode);
                   9940:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9941:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9942:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9943:                                              \%respnumlookup,\%startline);
                   9944:             if ($randompick && $total) {
                   9945:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9946:             }
1.677     raeburn  9947:         }
1.691     raeburn  9948:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9949:         chomp($scandata{$pid});
                   9950:         $scandata{$pid} =~ s/\r$//;
                   9951: 
1.523     raeburn  9952:         my $counter = -1;
1.677     raeburn  9953:         foreach my $resource (@mapresources) {
1.557     raeburn  9954:             my $parts;
1.554     raeburn  9955:             my $ressymb = $resource->symb();
1.557     raeburn  9956:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9957:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9958:                 my $currcode;
                   9959:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9960:                     $currcode = $scancode;
                   9961:                 }
1.557     raeburn  9962:                 (my $analysis,$parts) =
1.672     raeburn  9963:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9964:                                               $username,$domain,undef,
1.741     raeburn  9965:                                               $bubbles_per_row,$currcode);
1.557     raeburn  9966:             } else {
                   9967:                 $parts = $grader_partids_by_symb{$ressymb};
                   9968:             }
1.542     raeburn  9969:             ($counter,my $recording) =
                   9970:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9971:                                          $scandata{$pid},$parts,
1.691     raeburn  9972:                                          \%scantron_config,\%lettdig,$numletts,
                   9973:                                          $randomorder,$randompick,
                   9974:                                          \%respnumlookup,\%startline);
1.542     raeburn  9975:             $record{$pid} .= $recording;
1.523     raeburn  9976:         }
                   9977:     }
                   9978:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9979:     $r->print('<br />');
                   9980:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9981:     $passed = 0;
                   9982:     $failed = 0;
                   9983:     $numstudents = 0;
                   9984:     foreach my $last (sort(keys(%bylast))) {
                   9985:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9986:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9987:                 my $showscandata = $scandata{$pid};
                   9988:                 my $showrecord = $record{$pid};
                   9989:                 $showscandata =~ s/\s/&nbsp;/g;
                   9990:                 $showrecord =~ s/\s/&nbsp;/g;
                   9991:                 if ($scandata{$pid} eq $record{$pid}) {
                   9992:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9993:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9994: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9995: '</tr>'."\n".
                   9996: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9997: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9998:                     $passed ++;
                   9999:                 } else {
                   10000:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      10001:                     $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  10002: '</tr>'."\n".
                   10003: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   10004: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  10005: '</tr>'."\n";
                   10006:                     $failed ++;
                   10007:                 }
                   10008:                 $numstudents ++;
                   10009:             }
                   10010:         }
                   10011:     }
1.648     bisitz   10012:     $r->print(
                   10013:         '<p>'
                   10014:        .&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).',
                   10015:             '<b>',
                   10016:             $numstudents,
                   10017:             '</b>',
                   10018:             $env{'form.scantron_maxbubble'})
                   10019:        .'</p>'
                   10020:     );
1.682     raeburn  10021:     $r->print('<p>'
1.683     raeburn  10022:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  10023:              .'<br />'
                   10024:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   10025:              .'</p>'
                   10026:     );
1.523     raeburn  10027:     if ($passed) {
1.572     www      10028:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10029:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10030:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10031:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10032:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10033:                  $okstudents."\n".
                   10034:                  &Apache::loncommon::end_data_table().'<br />');
                   10035:     }
                   10036:     if ($failed) {
1.572     www      10037:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  10038:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   10039:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   10040:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   10041:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   10042:                  $badstudents."\n".
                   10043:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      10044:                  &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  10045:     }
1.614     www      10046:     $r->print('</form><br />');
1.523     raeburn  10047:     return;
                   10048: }
                   10049: 
1.542     raeburn  10050: sub verify_scantron_grading {
1.554     raeburn  10051:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  10052:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   10053:         $respnumlookup,$startline) = @_;
1.542     raeburn  10054:     my ($record,%expected,%startpos);
                   10055:     return ($counter,$record) if (!ref($resource));
                   10056:     return ($counter,$record) if (!$resource->is_problem());
                   10057:     my $symb = $resource->symb();
1.554     raeburn  10058:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   10059:     foreach my $part_id (@{$partids}) {
1.542     raeburn  10060:         $counter ++;
                   10061:         $expected{$part_id} = 0;
1.691     raeburn  10062:         my $respnum = $counter;
                   10063:         if ($randomorder || $randompick) {
                   10064:             $respnum = $respnumlookup->{$counter};
                   10065:             $startpos{$part_id} = $startline->{$counter} + 1;
                   10066:         } else {
                   10067:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   10068:         }
                   10069:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   10070:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  10071:             foreach my $item (@sub_lines) {
                   10072:                 $expected{$part_id} += $item;
                   10073:             }
                   10074:         } else {
1.691     raeburn  10075:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  10076:         }
                   10077:     }
                   10078:     if ($symb) {
                   10079:         my %recorded;
                   10080:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   10081:         if ($returnhash{'version'}) {
                   10082:             my %lasthash=();
                   10083:             my $version;
                   10084:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   10085:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   10086:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   10087:                 }
                   10088:             }
                   10089:             foreach my $key (keys(%lasthash)) {
                   10090:                 if ($key =~ /\.scantron$/) {
                   10091:                     my $value = &unescape($lasthash{$key});
                   10092:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   10093:                     if ($value eq '') {
                   10094:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10095:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   10096:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10097:                             }
                   10098:                         }
                   10099:                     } else {
                   10100:                         my @tocheck;
                   10101:                         my @items = split(//,$value);
                   10102:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   10103:                             ($scantron_config->{'Qon'} eq 'number')) {
                   10104:                             if (@items < $expected{$part_id}) {
                   10105:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   10106:                                 my @singles = split(//,$fragment);
                   10107:                                 foreach my $pos (@singles) {
                   10108:                                     if ($pos eq ' ') {
                   10109:                                         push(@tocheck,$pos);
                   10110:                                     } else {
                   10111:                                         my $next = shift(@items);
                   10112:                                         push(@tocheck,$next);
                   10113:                                     }
                   10114:                                 }
                   10115:                             } else {
                   10116:                                 @tocheck = @items;
                   10117:                             }
                   10118:                             foreach my $letter (@tocheck) {
                   10119:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   10120:                                     if ($letter !~ /^[A-J]$/) {
                   10121:                                         $letter = $scantron_config->{'Qoff'};
                   10122:                                     }
                   10123:                                     $recorded{$part_id} .= $letter;
                   10124:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   10125:                                     my $digit;
                   10126:                                     if ($letter !~ /^[A-J]$/) {
                   10127:                                         $digit = $scantron_config->{'Qoff'};
                   10128:                                     } else {
                   10129:                                         $digit = $lettdig->{$letter};
                   10130:                                     }
                   10131:                                     $recorded{$part_id} .= $digit;
                   10132:                                 }
                   10133:                             }
                   10134:                         } else {
                   10135:                             @tocheck = @items;
                   10136:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10137:                                 my $curr_sub = shift(@tocheck);
                   10138:                                 my $digit;
                   10139:                                 if ($curr_sub =~ /^[A-J]$/) {
                   10140:                                     $digit = $lettdig->{$curr_sub}-1;
                   10141:                                 }
                   10142:                                 if ($curr_sub eq 'J') {
                   10143:                                     $digit += scalar($numletts);
                   10144:                                 }
                   10145:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10146:                                     if ($j == $digit) {
                   10147:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   10148:                                     } else {
                   10149:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10150:                                     }
                   10151:                                 }
                   10152:                             }
                   10153:                         }
                   10154:                     }
                   10155:                 }
                   10156:             }
                   10157:         }
1.554     raeburn  10158:         foreach my $part_id (@{$partids}) {
1.542     raeburn  10159:             if ($recorded{$part_id} eq '') {
                   10160:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   10161:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   10162:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   10163:                     }
                   10164:                 }
                   10165:             }
                   10166:             $record .= $recorded{$part_id};
                   10167:         }
                   10168:     }
                   10169:     return ($counter,$record);
                   10170: }
                   10171: 
1.75      albertel 10172: #-------- end of section for handling grading scantron forms -------
                   10173: #
                   10174: #-------------------------------------------------------------------
                   10175: 
1.72      ng       10176: #-------------------------- Menu interface -------------------------
                   10177: #
1.614     www      10178: #--- Href with symb and command ---
                   10179: 
                   10180: sub href_symb_cmd {
                   10181:     my ($symb,$cmd)=@_;
1.669     raeburn  10182:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       10183: }
                   10184: 
1.443     banghart 10185: sub grading_menu {
1.608     www      10186:     my ($request,$symb) = @_;
1.443     banghart 10187:     if (!$symb) {return '';}
                   10188: 
                   10189:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      10190:                   'command'=>'individual');
1.538     schulted 10191:     
1.598     www      10192:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10193: 
                   10194:     $fields{'command'}='ungraded';
                   10195:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10196: 
                   10197:     $fields{'command'}='table';
                   10198:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10199: 
                   10200:     $fields{'command'}='all_for_one';
                   10201:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10202: 
1.621     www      10203:     $fields{'command'}='downloadfilesselect';
                   10204:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10205: 
1.443     banghart 10206:     $fields{'command'} = 'csvform';
1.538     schulted 10207:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10208:     
1.443     banghart 10209:     $fields{'command'} = 'processclicker';
1.538     schulted 10210:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   10211:     
1.443     banghart 10212:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 10213:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      10214: 
                   10215:     $fields{'command'} = 'initialverifyreceipt';
                   10216:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 10217:     
1.598     www      10218:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 10219:             items =>[
1.598     www      10220:                         {	linktext => 'Select individual students to grade',
                   10221:                     		url => $url1a,
1.538     schulted 10222:                     		permission => 'F',
1.636     wenzelju 10223:                     		icon => 'grade_students.png',
1.598     www      10224:                     		linktitle => 'Grade current resource for a selection of students.'
                   10225:                         }, 
1.764     raeburn  10226:                         {       linktext => 'Grade ungraded submissions',
1.598     www      10227:                                 url => $url1b,
                   10228:                                 permission => 'F',
1.636     wenzelju 10229:                                 icon => 'ungrade_sub.png',
1.598     www      10230:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 10231:                         },
1.598     www      10232: 
                   10233:                         {       linktext => 'Grading table',
                   10234:                                 url => $url1c,
                   10235:                                 permission => 'F',
1.636     wenzelju 10236:                                 icon => 'grading_table.png',
1.598     www      10237:                                 linktitle => 'Grade current resource for all students.'
                   10238:                         },
1.615     www      10239:                         {       linktext => 'Grade page/folder for one student',
1.598     www      10240:                                 url => $url1d,
                   10241:                                 permission => 'F',
1.636     wenzelju 10242:                                 icon => 'grade_PageFolder.png',
1.598     www      10243:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      10244:                         },
                   10245:                         {       linktext => 'Download submissions',
                   10246:                                 url => $url1e,
                   10247:                                 permission => 'F',
1.636     wenzelju 10248:                                 icon => 'download_sub.png',
1.621     www      10249:                                 linktitle => 'Download all students submissions.'
1.598     www      10250:                         }]},
                   10251:                          { categorytitle=>'Automated Grading',
                   10252:                items =>[
                   10253: 
1.538     schulted 10254:                 	    {	linktext => 'Upload Scores',
                   10255:                     		url => $url2,
                   10256:                     		permission => 'F',
                   10257:                     		icon => 'uploadscores.png',
                   10258:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   10259:                 	    },
                   10260:                 	    {	linktext => 'Process Clicker',
                   10261:                     		url => $url3,
                   10262:                     		permission => 'F',
                   10263:                     		icon => 'addClickerInfoFile.png',
                   10264:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   10265:                 	    },
1.587     raeburn  10266:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 10267:                     		url => $url4,
                   10268:                     		permission => 'F',
1.636     wenzelju 10269:                     		icon => 'bubblesheet.png',
1.648     bisitz   10270:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      10271:                 	    },
1.616     www      10272:                             {   linktext => 'Verify Receipt Number',
1.602     www      10273:                                 url => $url5,
                   10274:                                 permission => 'F',
1.636     wenzelju 10275:                                 icon => 'receipt_number.png',
1.602     www      10276:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   10277:                             }
                   10278: 
1.538     schulted 10279:                     ]
                   10280:             });
                   10281: 
1.443     banghart 10282:     # Create the menu
                   10283:     my $Str;
1.445     banghart 10284:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   10285:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      10286:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 10287: 
1.602     www      10288:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 10289:     return $Str;    
                   10290: }
                   10291: 
1.598     www      10292: sub ungraded {
                   10293:     my ($request)=@_;
                   10294:     &submit_options($request);
                   10295: }
                   10296: 
1.599     www      10297: sub submit_options_sequence {
1.608     www      10298:     my ($request,$symb) = @_;
1.599     www      10299:     if (!$symb) {return '';}
1.600     www      10300:     &commonJSfunctions($request);
                   10301:     my $result;
1.599     www      10302: 
1.600     www      10303:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10304:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      10305:     $result.=&selectfield(0).
1.601     www      10306:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      10307:             <div>
                   10308:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10309:             </div>
                   10310:         </div>
                   10311:   </form>';
                   10312:     return $result;
                   10313: }
                   10314: 
                   10315: sub submit_options_table {
1.608     www      10316:     my ($request,$symb) = @_;
1.600     www      10317:     if (!$symb) {return '';}
1.599     www      10318:     &commonJSfunctions($request);
1.746     raeburn  10319:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      10320:     my $result;
                   10321: 
                   10322:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10323:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      10324: 
1.745     raeburn  10325:     $result.=&selectfield(1,$is_tool).
1.601     www      10326:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      10327:             <div>
                   10328:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10329:             </div>
                   10330:         </div>
                   10331:   </form>';
                   10332:     return $result;
                   10333: }
1.443     banghart 10334: 
1.621     www      10335: sub submit_options_download {
                   10336:     my ($request,$symb) = @_;
                   10337:     if (!$symb) {return '';}
                   10338: 
1.746     raeburn  10339:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      10340:     &commonJSfunctions($request);
                   10341: 
                   10342:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   10343:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   10344:     $result.='
                   10345: <h2>
1.750     raeburn  10346:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  10347: </h2>'.&selectfield(1,$is_tool).'
1.621     www      10348:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   10349:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10350:             </div>
                   10351:           </div>
1.600     www      10352: 
                   10353: 
1.621     www      10354:   </form>';
                   10355:     return $result;
                   10356: }
                   10357: 
1.443     banghart 10358: #--- Displays the submissions first page -------
                   10359: sub submit_options {
1.608     www      10360:     my ($request,$symb) = @_;
1.72      ng       10361:     if (!$symb) {return '';}
                   10362: 
1.746     raeburn  10363:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       10364:     &commonJSfunctions($request);
1.473     albertel 10365:     my $result;
1.533     bisitz   10366: 
1.72      ng       10367:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      10368: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  10369:     $result.=&selectfield(1,$is_tool).'
1.601     www      10370:                 <input type="hidden" name="command" value="submission" /> 
                   10371: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   10372:             </div>
                   10373:           </div>
                   10374:   </form>';
                   10375:     return $result;
                   10376: }
1.533     bisitz   10377: 
1.601     www      10378: sub selectfield {
1.745     raeburn  10379:    my ($full,$is_tool)=@_;
                   10380:    my %options;
                   10381:    if ($is_tool) {
                   10382:        %options =
                   10383:            (&transtatus_options,
                   10384:             'select_form_order' => ['yes','incorrect','all']);
                   10385:    } else {
                   10386:        %options = 
                   10387:            (&substatus_options,
                   10388:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   10389:    }
1.601     www      10390:    my $result='<div class="LC_columnSection">
1.537     harmsja  10391:   
1.533     bisitz   10392:     <fieldset>
                   10393:       <legend>
                   10394:        '.&mt('Sections').'
                   10395:       </legend>
1.601     www      10396:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   10397:     </fieldset>
1.537     harmsja  10398:   
1.533     bisitz   10399:     <fieldset>
                   10400:       <legend>
                   10401:         '.&mt('Groups').'
                   10402:       </legend>
                   10403:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   10404:     </fieldset>
1.537     harmsja  10405:   
1.533     bisitz   10406:     <fieldset>
                   10407:       <legend>
                   10408:         '.&mt('Access Status').'
                   10409:       </legend>
1.601     www      10410:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   10411:     </fieldset>';
                   10412:     if ($full) {
1.745     raeburn  10413:         my $heading = &mt('Submission Status');
                   10414:         if ($is_tool) {
                   10415:             $heading = &mt('Transaction Status');
                   10416:         }
                   10417:         $result.='
1.533     bisitz   10418:     <fieldset>
                   10419:       <legend>
1.745     raeburn  10420:         '.$heading.'
1.601     www      10421:       </legend>'.
1.635     raeburn  10422:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      10423:    '</fieldset>';
                   10424:     }
                   10425:     $result.='</div><br />';
1.44      ng       10426:     return $result;
1.2       albertel 10427: }
                   10428: 
1.738     raeburn  10429: sub substatus_options {
                   10430:     return &Apache::lonlocal::texthash(
                   10431:                                       'yes'       => 'with submissions',
                   10432:                                       'queued'    => 'in grading queue',
                   10433:                                       'graded'    => 'with ungraded submissions',
                   10434:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10435:                                       'all'       => 'with any status',
                   10436:                                       );
1.738     raeburn  10437: }
                   10438: 
1.745     raeburn  10439: sub transtatus_options {
                   10440:     return &Apache::lonlocal::texthash(
                   10441:                                        'yes'       => 'with score transactions',
                   10442:                                        'incorrect' => 'with less than full credit',
                   10443:                                        'all'       => 'with any status',
                   10444:                                       );
                   10445: }
                   10446: 
1.285     albertel 10447: sub reset_perm {
                   10448:     undef(%perm);
                   10449: }
                   10450: 
                   10451: sub init_perm {
                   10452:     &reset_perm();
1.770     raeburn  10453:     foreach my $test_perm ('vgr','mgr','opa','usc') {
1.300     albertel 10454: 
                   10455: 	my $scope = $env{'request.course.id'};
                   10456: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10457: 
                   10458: 	    $scope .= '/'.$env{'request.course.sec'};
                   10459: 	    if ( $perm{$test_perm}=
                   10460: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10461: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10462: 	    } else {
                   10463: 		delete($perm{$test_perm});
                   10464: 	    }
1.285     albertel 10465: 	}
                   10466:     }
                   10467: }
                   10468: 
1.674     raeburn  10469: sub init_old_essays {
                   10470:     my ($symb,$apath,$adom,$aname) = @_;
                   10471:     if ($symb ne '') {
                   10472:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10473:         if (keys(%essays) > 0) {
                   10474:             $old_essays{$symb} = \%essays;
                   10475:         }
                   10476:     }
                   10477:     return;
                   10478: }
                   10479: 
                   10480: sub reset_old_essays {
                   10481:     undef(%old_essays);
                   10482: }
                   10483: 
1.400     www      10484: sub gather_clicker_ids {
1.408     albertel 10485:     my %clicker_ids;
1.400     www      10486: 
                   10487:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10488: 
                   10489:     # Set up a couple variables.
1.407     albertel 10490:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10491:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10492:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10493: 
1.407     albertel 10494:     foreach my $student (keys(%$classlist)) {
1.438     www      10495:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10496:         my $username = $classlist->{$student}->[$username_idx];
                   10497:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10498:         my $clickers =
1.408     albertel 10499: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10500:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10501:             $id=~s/^[\#0]+//;
1.421     www      10502:             $id=~s/[\-\:]//g;
1.407     albertel 10503:             if (exists($clicker_ids{$id})) {
1.408     albertel 10504: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10505:             } else {
1.408     albertel 10506: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10507:             }
                   10508:         }
                   10509:     }
1.407     albertel 10510:     return %clicker_ids;
1.400     www      10511: }
                   10512: 
1.402     www      10513: sub gather_adv_clicker_ids {
1.408     albertel 10514:     my %clicker_ids;
1.402     www      10515:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10516:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10517:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10518:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10519:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10520:             my ($puname,$pudom)=split(/\:/,$person);
                   10521:             my $clickers =
1.408     albertel 10522: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10523:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10524: 		$id=~s/^[\#0]+//;
1.421     www      10525:                 $id=~s/[\-\:]//g;
1.408     albertel 10526: 		if (exists($clicker_ids{$id})) {
                   10527: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10528: 		} else {
                   10529: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10530: 		}
1.405     www      10531:             }
1.402     www      10532:         }
                   10533:     }
1.407     albertel 10534:     return %clicker_ids;
1.402     www      10535: }
                   10536: 
1.413     www      10537: sub clicker_grading_parameters {
                   10538:     return ('gradingmechanism' => 'scalar',
                   10539:             'upfiletype' => 'scalar',
                   10540:             'specificid' => 'scalar',
                   10541:             'pcorrect' => 'scalar',
                   10542:             'pincorrect' => 'scalar');
                   10543: }
                   10544: 
1.400     www      10545: sub process_clicker {
1.608     www      10546:     my ($r,$symb)=@_;
1.400     www      10547:     if (!$symb) {return '';}
                   10548:     my $result=&checkforfile_js();
1.632     www      10549:     $result.=&Apache::loncommon::start_data_table().
                   10550:              &Apache::loncommon::start_data_table_header_row().
                   10551:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10552:              &Apache::loncommon::end_data_table_header_row().
                   10553:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10554: # Attempt to restore parameters from last session, set defaults if not present
                   10555:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10556:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10557:                                                  \%Saveable_Parameters);
                   10558:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10559:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10560:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10561:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10562: 
                   10563:     my %checked;
1.521     www      10564:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10565:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10566:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10567:        }
                   10568:     }
                   10569: 
1.632     www      10570:     my $upload=&mt("Evaluate File");
1.400     www      10571:     my $type=&mt("Type");
1.402     www      10572:     my $attendance=&mt("Award points just for participation");
                   10573:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10574:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10575:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10576:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10577:     my $pcorrect=&mt("Percentage points for correct solution");
                   10578:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10579:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10580: 						   {'iclicker' => 'i>clicker',
1.666     www      10581:                                                     'interwrite' => 'interwrite PRS',
                   10582:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10583:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10584:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10585: function sanitycheck() {
                   10586: // Accept only integer percentages
                   10587:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10588:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10589: // Find out grading choice
                   10590:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10591:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10592:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10593:       }
                   10594:    }
                   10595: // By default, new choice equals user selection
                   10596:    newgradingchoice=gradingchoice;
                   10597: // Not good to give more points for false answers than correct ones
                   10598:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10599:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10600:    }
                   10601: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10602:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10603:       document.forms.gradesupload.pcorrect.value=100;
                   10604:       document.forms.gradesupload.pincorrect.value=100;
                   10605:    }
                   10606: // If the values are different, cannot be attendance only
                   10607:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10608:        (gradingchoice=='attendance')) {
                   10609:        newgradingchoice='personnel';
                   10610:    }
                   10611: // Change grading choice to new one
                   10612:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10613:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10614:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10615:       } else {
                   10616:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10617:       }
                   10618:    }
                   10619: // Remember the old state
                   10620:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10621: }
1.597     wenzelju 10622: ENDUPFORM
                   10623:     $result.= <<ENDUPFORM;
1.400     www      10624: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10625: <input type="hidden" name="symb" value="$symb" />
                   10626: <input type="hidden" name="command" value="processclickerfile" />
                   10627: <input type="file" name="upfile" size="50" />
                   10628: <br /><label>$type: $selectform</label>
1.632     www      10629: ENDUPFORM
                   10630:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10631:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10632:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10633: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10634: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10635: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10636: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10637: <br />&nbsp;&nbsp;&nbsp;
                   10638: <input type="text" name="givenanswer" size="50" />
1.413     www      10639: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10640: ENDGRADINGFORM
1.766     raeburn  10641:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
1.632     www      10642:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10643:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10644: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10645: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.767     raeburn  10646: </form>
1.632     www      10647: ENDPERCFORM
                   10648:     $result.='</td>'.
                   10649:              &Apache::loncommon::end_data_table_row().
                   10650:              &Apache::loncommon::end_data_table();
1.400     www      10651:     return $result;
                   10652: }
                   10653: 
                   10654: sub process_clicker_file {
1.766     raeburn  10655:     my ($r,$symb) = @_;
1.400     www      10656:     if (!$symb) {return '';}
1.413     www      10657: 
                   10658:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10659:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10660:                                               \%Saveable_Parameters);
1.598     www      10661:     my $result='';
1.404     www      10662:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10663: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10664: 	return $result;
1.404     www      10665:     }
1.522     www      10666:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10667:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10668:         return $result;
1.521     www      10669:     }
1.522     www      10670:     my $foundgiven=0;
1.521     www      10671:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10672:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10673:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10674:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10675:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10676:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10677:         $foundgiven=$#answers+1;
1.521     www      10678:     }
1.407     albertel 10679:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10680:     my %correct_ids;
1.404     www      10681:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10682: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10683:     }
                   10684:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10685: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10686: 	   $correct_id=~tr/a-z/A-Z/;
                   10687: 	   $correct_id=~s/\s//gs;
                   10688: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10689:            $correct_id=~s/[\-\:]//g;
1.414     www      10690:            if ($correct_id) {
                   10691: 	      $correct_ids{$correct_id}='specified';
                   10692:            }
                   10693:         }
1.400     www      10694:     }
1.404     www      10695:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10696: 	$result.=&mt('Score based on attendance only');
1.521     www      10697:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10698:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10699:     } else {
1.408     albertel 10700: 	my $number=0;
1.411     www      10701: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10702: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10703: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10704: 	    if ($correct_ids{$id} eq 'specified') {
                   10705: 		$result.=&mt('specified');
                   10706: 	    } else {
                   10707: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10708: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10709: 	    }
                   10710: 	    $number++;
                   10711: 	}
1.411     www      10712:         $result.="</p>\n";
1.710     bisitz   10713:         if ($number==0) {
                   10714:             $result .=
                   10715:                  &Apache::lonhtmlcommon::confirm_success(
                   10716:                      &mt('No IDs found to determine correct answer'),1);
                   10717:             return $result;
                   10718:         }
1.404     www      10719:     }
1.405     www      10720:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10721:         $result .=
                   10722:             &Apache::lonhtmlcommon::confirm_success(
                   10723:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10724:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10725:         return $result;
1.405     www      10726:     }
1.760     raeburn  10727:     my $mimetype;
                   10728:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10729:         my $mm = new File::MMagic;
                   10730:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10731:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10732:             $result.= '<p>'.
                   10733:                 &Apache::lonhtmlcommon::confirm_success(
                   10734:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   10735:             return $result;
                   10736:         }
                   10737:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10738:         $result .= '<p>'.
                   10739:             &Apache::lonhtmlcommon::confirm_success(
                   10740:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   10741:         return $result;
                   10742:     }
1.410     www      10743: 
                   10744: # Were able to get all the info needed, now analyze the file
                   10745: 
1.411     www      10746:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10747:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10748:     $result.=&Apache::loncommon::start_data_table().
                   10749:              &Apache::loncommon::start_data_table_header_row().
                   10750:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10751:              &Apache::loncommon::end_data_table_header_row().
                   10752:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10753: <td>
1.410     www      10754: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10755: <input type="hidden" name="symb" value="$symb" />
                   10756: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10757: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10758: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10759: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10760: ENDHEADER
1.522     www      10761:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10762:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10763:     } 
1.408     albertel 10764:     my %responses;
                   10765:     my @questiontitles;
1.405     www      10766:     my $errormsg='';
                   10767:     my $number=0;
                   10768:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  10769:         if ($mimetype eq 'text/plain') {
                   10770:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10771:         } elsif ($mimetype eq 'text/html') {
                   10772:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10773:         }
                   10774:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10775:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  10776:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      10777:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10778:     }
1.411     www      10779:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10780:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10781:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10782:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10783:              '<br />';
1.522     www      10784:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10785:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10786:        return $result;
1.522     www      10787:     } 
1.414     www      10788: # Remember Question Titles
                   10789: # FIXME: Possibly need delimiter other than ":"
                   10790:     for (my $i=0;$i<$number;$i++) {
                   10791:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10792:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10793:     }
1.411     www      10794:     my $correct_count=0;
                   10795:     my $student_count=0;
                   10796:     my $unknown_count=0;
1.414     www      10797: # Match answers with usernames
                   10798: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10799:     foreach my $id (keys(%responses)) {
1.410     www      10800:        if ($correct_ids{$id}) {
1.414     www      10801:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10802:           $correct_count++;
1.410     www      10803:        } elsif ($clicker_ids{$id}) {
1.437     www      10804:           if ($clicker_ids{$id}=~/\,/) {
                   10805: # More than one user with the same clicker!
1.632     www      10806:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10807:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10808:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10809:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10810:                            "<select name='multi".$id."'>";
                   10811:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10812:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10813:              }
                   10814:              $result.='</select>';
                   10815:              $unknown_count++;
                   10816:           } else {
                   10817: # Good: found one and only one user with the right clicker
                   10818:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10819:              $student_count++;
                   10820:           }
1.410     www      10821:        } else {
1.632     www      10822:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10823:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10824:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10825:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10826:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10827:                    "\n".&mt("Domain").": ".
                   10828:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.762     raeburn  10829:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
1.411     www      10830:           $unknown_count++;
1.410     www      10831:        }
1.405     www      10832:     }
1.412     www      10833:     $result.='<hr />'.
                   10834:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10835:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10836:        if ($correct_count==0) {
1.696     bisitz   10837:           $errormsg.="Found no correct answers for grading!";
1.412     www      10838:        } elsif ($correct_count>1) {
1.414     www      10839:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10840:        }
                   10841:     }
1.428     www      10842:     if ($number<1) {
                   10843:        $errormsg.="Found no questions.";
                   10844:     }
1.412     www      10845:     if ($errormsg) {
                   10846:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10847:     } else {
                   10848:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10849:     }
1.632     www      10850:     $result.='</form></td>'.
                   10851:              &Apache::loncommon::end_data_table_row().
                   10852:              &Apache::loncommon::end_data_table();
1.614     www      10853:     return $result;
1.400     www      10854: }
                   10855: 
1.405     www      10856: sub iclicker_eval {
1.406     www      10857:     my ($questiontitles,$responses)=@_;
1.405     www      10858:     my $number=0;
                   10859:     my $errormsg='';
                   10860:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10861:         my %components=&Apache::loncommon::record_sep($line);
                   10862:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10863: 	if ($entries[0] eq 'Question') {
                   10864: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10865: 		$$questiontitles[$number]=$entries[$i];
                   10866: 		$number++;
                   10867: 	    }
                   10868: 	}
                   10869: 	if ($entries[0]=~/^\#/) {
                   10870: 	    my $id=$entries[0];
                   10871: 	    my @idresponses;
                   10872: 	    $id=~s/^[\#0]+//;
                   10873: 	    for (my $i=0;$i<$number;$i++) {
                   10874: 		my $idx=3+$i*6;
1.644     www      10875:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10876: 		push(@idresponses,$entries[$idx]);
                   10877: 	    }
                   10878: 	    $$responses{$id}=join(',',@idresponses);
                   10879: 	}
1.405     www      10880:     }
                   10881:     return ($errormsg,$number);
                   10882: }
                   10883: 
1.760     raeburn  10884: sub iclickerxml_eval {
                   10885:     my ($questiontitles,$responses)=@_;
                   10886:     my $number=0;
                   10887:     my $errormsg='';
                   10888:     my @state;
                   10889:     my %respbyid;
                   10890:     my $p = HTML::Parser->new
                   10891:     (
                   10892:         xml_mode => 1,
                   10893:         start_h =>
                   10894:             [sub {
                   10895:                  my ($tagname,$attr) = @_;
                   10896:                  push(@state,$tagname);
                   10897:                  if ("@state" eq "ssn p") {
                   10898:                      my $title = $attr->{qn};
                   10899:                      $title =~ s/(^\s+|\s+$)//g;
                   10900:                      $questiontitles->[$number]=$title;
                   10901:                  } elsif ("@state" eq "ssn p v") {
                   10902:                      my $id = $attr->{id};
                   10903:                      my $entry = $attr->{ans};
                   10904:                      $id=~s/^[\#0]+//;
                   10905:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10906:                      $respbyid{$id}[$number] = $entry;
                   10907:                  }
                   10908:             }, "tagname, attr"],
                   10909:          end_h =>
                   10910:                [sub {
                   10911:                    my ($tagname) = @_;
                   10912:                    if ("@state" eq "ssn p") {
                   10913:                        $number++;
                   10914:                    }
                   10915:                    pop(@state);
                   10916:                 }, "tagname"],
                   10917:     );
                   10918: 
                   10919:     $p->parse($env{'form.upfile'});
                   10920:     $p->eof;
                   10921:     foreach my $id (keys(%respbyid)) {
                   10922:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10923:     }
                   10924:     return ($errormsg,$number);
                   10925: }
                   10926: 
1.419     www      10927: sub interwrite_eval {
                   10928:     my ($questiontitles,$responses)=@_;
                   10929:     my $number=0;
                   10930:     my $errormsg='';
1.420     www      10931:     my $skipline=1;
                   10932:     my $questionnumber=0;
                   10933:     my %idresponses=();
1.419     www      10934:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10935:         my %components=&Apache::loncommon::record_sep($line);
                   10936:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10937:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10938:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10939:         next if $skipline;
                   10940:         if ($entries[0]!=$questionnumber) {
                   10941:            $questionnumber=$entries[0];
                   10942:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10943:            $number++;
1.419     www      10944:         }
1.420     www      10945:         my $id=$entries[4];
                   10946:         $id=~s/^[\#0]+//;
1.421     www      10947:         $id=~s/^v\d*\://i;
                   10948:         $id=~s/[\-\:]//g;
1.420     www      10949:         $idresponses{$id}[$number]=$entries[6];
                   10950:     }
1.524     raeburn  10951:     foreach my $id (keys(%idresponses)) {
1.420     www      10952:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10953:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10954:     }
                   10955:     return ($errormsg,$number);
                   10956: }
                   10957: 
1.666     www      10958: sub turning_eval {
                   10959:     my ($questiontitles,$responses)=@_;
                   10960:     my $number=0;
                   10961:     my $errormsg='';
                   10962:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10963:         my %components=&Apache::loncommon::record_sep($line);
                   10964:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10965:         if ($#entries>$number) { $number=$#entries; }
                   10966:         my $id=$entries[0];
                   10967:         my @idresponses;
                   10968:         $id=~s/^[\#0]+//;
                   10969:         unless ($id) { next; }
                   10970:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10971:             $entries[$idx]=~s/\,/\;/g;
                   10972:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10973:             push(@idresponses,$entries[$idx]);
                   10974:         }
                   10975:         $$responses{$id}=join(',',@idresponses);
                   10976:     }
                   10977:     for (my $i=1; $i<=$number; $i++) {
                   10978:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10979:     }
                   10980:     return ($errormsg,$number);
                   10981: }
                   10982: 
                   10983: 
1.414     www      10984: sub assign_clicker_grades {
1.766     raeburn  10985:     my ($r,$symb) = @_;
1.414     www      10986:     if (!$symb) {return '';}
1.416     www      10987: # See which part we are saving to
1.582     raeburn  10988:     my $res_error;
                   10989:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10990:     if ($res_error) {
                   10991:         return &navmap_errormsg();
                   10992:     }
1.416     www      10993: # FIXME: This should probably look for the first handgradeable part
                   10994:     my $part=$$partlist[0];
                   10995: # Start screen output
1.766     raeburn  10996:     my $result = &Apache::loncommon::start_data_table().
                   10997:                  &Apache::loncommon::start_data_table_header_row().
                   10998:                  '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10999:                  &Apache::loncommon::end_data_table_header_row().
                   11000:                  &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      11001: # Get correct result
                   11002: # FIXME: Possibly need delimiter other than ":"
                   11003:     my @correct=();
1.415     www      11004:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   11005:     my $number=$env{'form.number'};
                   11006:     if ($gradingmechanism ne 'attendance') {
1.414     www      11007:        foreach my $key (keys(%env)) {
                   11008:           if ($key=~/^form\.correct\:/) {
                   11009:              my @input=split(/\,/,$env{$key});
                   11010:              for (my $i=0;$i<=$#input;$i++) {
                   11011:                  if (($correct[$i]) && ($input[$i]) &&
                   11012:                      ($correct[$i] ne $input[$i])) {
                   11013:                     $result.='<br /><span class="LC_warning">'.
                   11014:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   11015:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      11016:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      11017:                     $correct[$i]=$input[$i];
                   11018:                  }
                   11019:              }
                   11020:           }
                   11021:        }
1.415     www      11022:        for (my $i=0;$i<$number;$i++) {
1.644     www      11023:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      11024:              $result.='<br /><span class="LC_error">'.
                   11025:                       &mt('No correct result given for question "[_1]"!',
                   11026:                           $env{'form.question:'.$i}).'</span>';
                   11027:           }
                   11028:        }
1.644     www      11029:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      11030:     }
                   11031: # Start grading
1.415     www      11032:     my $pcorrect=$env{'form.pcorrect'};
                   11033:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      11034:     my $storecount=0;
1.632     www      11035:     my %users=();
1.415     www      11036:     foreach my $key (keys(%env)) {
1.420     www      11037:        my $user='';
1.415     www      11038:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      11039:           $user=$1;
                   11040:        }
                   11041:        if ($key=~/^form\.unknown\:(.*)$/) {
                   11042:           my $id=$1;
                   11043:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   11044:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      11045:           } elsif ($env{'form.multi'.$id}) {
                   11046:              $user=$env{'form.multi'.$id};
1.420     www      11047:           }
                   11048:        }
1.632     www      11049:        if ($user) {
                   11050:           if ($users{$user}) {
                   11051:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   11052:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      11053:                       '</span><br />';
                   11054:           }
                   11055:           $users{$user}=1; 
1.415     www      11056:           my @answer=split(/\,/,$env{$key});
                   11057:           my $sum=0;
1.522     www      11058:           my $realnumber=$number;
1.415     www      11059:           for (my $i=0;$i<$number;$i++) {
1.576     www      11060:              if  ($correct[$i] eq '-') {
                   11061:                 $realnumber--;
1.766     raeburn  11062:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
1.415     www      11063:                 if ($gradingmechanism eq 'attendance') {
                   11064:                    $sum+=$pcorrect;
1.576     www      11065:                 } elsif ($correct[$i] eq '*') {
1.522     www      11066:                    $sum+=$pcorrect;
1.415     www      11067:                 } else {
1.644     www      11068: # We actually grade if correct or not
                   11069:                    my $increment=$pincorrect;
                   11070: # Special case: numerical answer "0"
                   11071:                    if ($correct[$i] eq '0') {
                   11072:                       if ($answer[$i]=~/^[0\.]+$/) {
                   11073:                          $increment=$pcorrect;
                   11074:                       }
                   11075: # General numerical answer, both evaluate to something non-zero
                   11076:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   11077:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   11078:                          $increment=$pcorrect;
                   11079:                       }
                   11080: # Must be just alphanumeric
                   11081:                    } elsif ($answer[$i] eq $correct[$i]) {
                   11082:                       $increment=$pcorrect;
1.415     www      11083:                    }
1.644     www      11084:                    $sum+=$increment;
1.415     www      11085:                 }
                   11086:              }
                   11087:           }
1.522     www      11088:           my $ave=$sum/(100*$realnumber);
1.416     www      11089: # Store
                   11090:           my ($username,$domain)=split(/\:/,$user);
                   11091:           my %grades=();
                   11092:           $grades{"resource.$part.solved"}='correct_by_override';
                   11093:           $grades{"resource.$part.awarded"}=$ave;
                   11094:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   11095:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   11096:                                                  $env{'request.course.id'},
                   11097:                                                  $domain,$username);
                   11098:           if ($returncode ne 'ok') {
                   11099:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   11100:           } else {
                   11101:              $storecount++;
                   11102:           }
1.415     www      11103:        }
                   11104:     }
                   11105: # We are done
1.549     hauer    11106:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      11107:              '</td>'.
                   11108:              &Apache::loncommon::end_data_table_row().
                   11109:              &Apache::loncommon::end_data_table();
1.614     www      11110:     return $result;
1.414     www      11111: }
                   11112: 
1.582     raeburn  11113: sub navmap_errormsg {
                   11114:     return '<div class="LC_error">'.
                   11115:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  11116:            &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  11117:            '</div>';
                   11118: }
1.607     droeschl 11119: 
1.609     www      11120: sub startpage {
1.754     raeburn  11121:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload) = @_;
                   11122:     my %args;
                   11123:     if ($onload) {
                   11124:          my %loaditems = (
                   11125:                         'onload' => $onload,
                   11126:                       );
                   11127:          $args{'add_entries'} = \%loaditems;
                   11128:     }
1.671     raeburn  11129:     if ($nomenu) {
1.754     raeburn  11130:         $args{'only_body'} = 1; 
1.759     raeburn  11131:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
1.671     raeburn  11132:     } else {
                   11133:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.754     raeburn  11134:         $args{'bread_crumbs'} = $crumbs;
                   11135:         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
1.765     raeburn  11136:         if ($env{'request.course.id'}) {
                   11137:             &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   11138:         }
1.671     raeburn  11139:     }
1.613     www      11140:     unless ($nodisplayflag) {
1.759     raeburn  11141:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      11142:     }
1.607     droeschl 11143: }
1.582     raeburn  11144: 
1.622     www      11145: sub select_problem {
                   11146:     my ($r)=@_;
1.632     www      11147:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.771   ! raeburn  11148:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,1,1));
1.622     www      11149:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   11150:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   11151: }
                   11152: 
1.1       albertel 11153: sub handler {
1.41      ng       11154:     my $request=$_[0];
1.434     albertel 11155:     &reset_caches();
1.646     raeburn  11156:     if ($request->header_only) {
                   11157:         &Apache::loncommon::content_type($request,'text/html');
                   11158:         $request->send_http_header;
                   11159:         return OK;
                   11160:     }
                   11161:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   11162: 
1.664     raeburn  11163: # see what command we need to execute
                   11164: 
                   11165:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   11166:     my $command=$commands[0];
                   11167: 
1.646     raeburn  11168:     &init_perm();
                   11169:     if (!$env{'request.course.id'}) {
1.664     raeburn  11170:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   11171:                 ($command =~ /^scantronupload/)) {
                   11172:             # Not in a course.
                   11173:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   11174:             return HTTP_NOT_ACCEPTABLE;
                   11175:         }
1.646     raeburn  11176:     } elsif (!%perm) {
                   11177:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  11178:         return OK;
1.41      ng       11179:     }
1.646     raeburn  11180:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       11181:     $request->send_http_header;
1.646     raeburn  11182: 
1.160     albertel 11183:     if ($#commands > 0) {
                   11184: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   11185:     }
1.608     www      11186: 
                   11187: # see what the symb is
                   11188: 
                   11189:     my $symb=$env{'form.symb'};
                   11190:     unless ($symb) {
                   11191:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   11192:        $symb=&Apache::lonnet::symbread($url);
                   11193:     }
1.646     raeburn  11194:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      11195: 
1.513     foxr     11196:     $ssi_error = 0;
1.637     www      11197:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      11198: #
1.637     www      11199: # Not called from a resource, but inside a course
1.601     www      11200: #    
1.622     www      11201:         &startpage($request,undef,[],1,1);
                   11202:         &select_problem($request);
1.41      ng       11203:     } else {
1.104     albertel 11204: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  11205:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   11206:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   11207:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11208:                     &choose_task_version_form($symb,$env{'form.student'},
                   11209:                                               $env{'form.userdom'});
                   11210:             }
                   11211:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   11212:             if ($versionform) {
                   11213:                 $request->print($versionform);
                   11214:             }
                   11215:             $request->print('<br clear="all" />');
1.611     www      11216: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  11217:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   11218:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   11219:                 &choose_task_version_form($symb,$env{'form.student'},
                   11220:                                           $env{'form.userdom'},
                   11221:                                           $env{'form.inhibitmenu'});
                   11222:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   11223:             if ($versionform) {
                   11224:                 $request->print($versionform);
                   11225:             }
                   11226:             $request->print('<br clear="all" />');
                   11227:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 11228: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      11229:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11230:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      11231: 	    &pickStudentPage($request,$symb);
1.103     albertel 11232: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      11233:             &startpage($request,$symb,
                   11234:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11235:                                        {href=>'',text=>'Select student'},
                   11236:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      11237: 	    &displayPage($request,$symb);
1.104     albertel 11238: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      11239:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   11240:                                        {href=>'',text=>'Select student'},
                   11241:                                        {href=>'',text=>'Grade student'},
                   11242:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      11243: 	    &updateGradeByPage($request,$symb);
1.104     albertel 11244: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      11245:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11246:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      11247: 	    &processGroup($request,$symb);
1.104     albertel 11248: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      11249:             &startpage($request,$symb);
                   11250: 	    $request->print(&grading_menu($request,$symb));
1.598     www      11251: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      11252:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      11253: 	    $request->print(&submit_options($request,$symb));
1.598     www      11254:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      11255:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   11256:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      11257:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      11258:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      11259:             $request->print(&submit_options_table($request,$symb));
1.598     www      11260:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      11261:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      11262:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 11263: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      11264:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      11265: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 11266: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      11267:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   11268:                                        {href=>'',text=>'Store grades'}]);
1.608     www      11269: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 11270: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      11271:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   11272:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   11273:                                                                              text=>"Modify grades"},
                   11274:                                        {href=>'', text=>"Store grades"}]);
1.608     www      11275: 	    $request->print(&editgrades($request,$symb));
1.602     www      11276:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      11277:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      11278:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 11279: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      11280:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   11281:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      11282: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      11283:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      11284:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      11285:             $request->print(&process_clicker($request,$symb));
1.400     www      11286:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      11287:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11288:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      11289:             $request->print(&process_clicker_file($request,$symb));
1.414     www      11290:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      11291:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   11292:                                        {href=>'', text=>'Process clicker file'},
                   11293:                                        {href=>'', text=>'Store grades'}]);
1.608     www      11294:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 11295: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      11296:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11297: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 11298: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      11299:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11300: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 11301: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      11302:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11303: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 11304: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 11305: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      11306:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11307: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       11308: 	    } else {
1.257     albertel 11309: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   11310: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       11311: 		} else {
1.257     albertel 11312: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       11313: 		}
1.627     www      11314:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11315: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       11316: 	    }
1.246     albertel 11317: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      11318:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      11319: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 11320: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  11321:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11322:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      11323: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 11324:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      11325:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11326:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 11327: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      11328:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11329: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 11330: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      11331:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11332: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 11333:  	} elsif ($command eq 'scantronupload' && 
1.770     raeburn  11334:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.754     raeburn  11335:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   11336:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      11337:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 11338:  	} elsif ($command eq 'scantronupload_save' &&
1.770     raeburn  11339:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
1.616     www      11340:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11341:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.770     raeburn  11342:  	} elsif ($command eq 'scantron_download' && ($perm{'usc'} || $perm{'mgr'})) {
1.616     www      11343:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      11344:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.770     raeburn  11345:         } elsif ($command eq 'scantronupload_delete' &&
                   11346:                  (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) || $perm{'usc'})) {
                   11347:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
                   11348:             &scantron_upload_delete($request,$symb);
1.523     raeburn  11349:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      11350:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      11351:             $request->print(&checkscantron_results($request,$symb));
                   11352:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   11353:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   11354:             $request->print(&submit_options_download($request,$symb));
                   11355:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   11356:             &startpage($request,$symb,
                   11357:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.750     raeburn  11358:     {href=>'', text=>'Download submitted files'}]);
1.621     www      11359:             &submit_download_link($request,$symb);
1.106     albertel 11360: 	} elsif ($command) {
1.620     www      11361:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   11362: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 11363: 	}
1.2       albertel 11364:     }
1.513     foxr     11365:     if ($ssi_error) {
                   11366: 	&ssi_print_error($request);
                   11367:     }
1.671     raeburn  11368:     if ($env{'form.inhibitmenu'}) {
                   11369:         $request->print(&Apache::loncommon::end_page());
1.765     raeburn  11370:     } elsif ($env{'request.course.id'}) {
1.671     raeburn  11371:         &Apache::lonquickgrades::endGradeScreen($request);
                   11372:     }
1.434     albertel 11373:     &reset_caches();
1.646     raeburn  11374:     return OK;
1.44      ng       11375: }
                   11376: 
1.1       albertel 11377: 1;
                   11378: 
1.13      albertel 11379: __END__;
1.531     jms      11380: 
                   11381: 
                   11382: =head1 NAME
                   11383: 
                   11384: Apache::grades
                   11385: 
                   11386: =head1 SYNOPSIS
                   11387: 
                   11388: Handles the viewing of grades.
                   11389: 
                   11390: This is part of the LearningOnline Network with CAPA project
                   11391: described at http://www.lon-capa.org.
                   11392: 
                   11393: =head1 OVERVIEW
                   11394: 
                   11395: Do an ssi with retries:
1.715     bisitz   11396: While I'd love to factor out this with the version in lonprintout,
1.531     jms      11397: 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
                   11398: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   11399: 
                   11400: At least the logic that drives this has been pulled out into loncommon.
                   11401: 
                   11402: 
                   11403: 
                   11404: ssi_with_retries - Does the server side include of a resource.
                   11405:                      if the ssi call returns an error we'll retry it up to
                   11406:                      the number of times requested by the caller.
1.715     bisitz   11407:                      If we still have a problem, no text is appended to the
1.531     jms      11408:                      output and we set some global variables.
                   11409:                      to indicate to the caller an SSI error occurred.  
                   11410:                      All of this is supposed to deal with the issues described
1.715     bisitz   11411:                      in LON-CAPA BZ 5631 see:
1.531     jms      11412:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   11413:                      by informing the user that this happened.
                   11414: 
                   11415: Parameters:
                   11416:   resource   - The resource to include.  This is passed directly, without
                   11417:                interpretation to lonnet::ssi.
                   11418:   form       - The form hash parameters that guide the interpretation of the resource
                   11419:                
                   11420:   retries    - Number of retries allowed before giving up completely.
                   11421: Returns:
                   11422:   On success, returns the rendered resource identified by the resource parameter.
                   11423: Side Effects:
                   11424:   The following global variables can be set:
                   11425:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   11426:                               It is up to the caller to initialize this to false
                   11427:                               if desired.
                   11428:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11429:                               of the resource that could not be rendered by the ssi
                   11430:                               call.
                   11431:    ssi_error_message   - The error string fetched from the ssi response
                   11432:                               in the event of an error.
                   11433: 
                   11434: 
                   11435: =head1 HANDLER SUBROUTINE
                   11436: 
                   11437: ssi_with_retries()
                   11438: 
                   11439: =head1 SUBROUTINES
                   11440: 
                   11441: =over
                   11442: 
1.671     raeburn  11443: =head1 Routines to display previous version of a Task for a specific student
                   11444: 
                   11445: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11446: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11447: requires a proctor to check-in the student, a new version of the Task will
                   11448: be created when the student is checked in to the new opportunity.
                   11449: 
                   11450: If a particular student has tried two or more versions of a particular task,
                   11451: the submission screen provides a user with vgr privileges (e.g., a Course
                   11452: Coordinator) the ability to display a previous version worked on by the
                   11453: student.  By default, the current version is displayed. If a previous version
                   11454: has been selected for display, submission data are only shown that pertain
                   11455: to that particular version, and the interface to submit grades is not shown.
                   11456: 
                   11457: =over 4
                   11458: 
                   11459: =item show_previous_task_version()
                   11460: 
                   11461: Displays a specified version of a student's Task, as the student sees it.
                   11462: 
                   11463: Inputs: 2
                   11464:         request - request object
                   11465:         symb    - unique symb for current instance of resource
                   11466: 
                   11467: Output: None.
                   11468: 
                   11469: Side Effects: calls &show_problem() to print version of Task, with
                   11470:               version contained in form item: $env{'form.previousversion'}
                   11471: 
                   11472: =item choose_task_version_form()
                   11473: 
                   11474: Displays a web form used to select which version of a student's view of a
                   11475: Task should be displayed.  Either launches a pop-up window, or replaces
                   11476: content in existing pop-up, or replaces page in main window.
                   11477: 
                   11478: Inputs: 4
                   11479:         symb    - unique symb for current instance of resource
                   11480:         uname   - username of student
                   11481:         udom    - domain of student
                   11482:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11483:                   breadcrumbs etc., are displayed
                   11484: 
                   11485: Output: 4
                   11486:         current   - student's current version
                   11487:         displayed - student's version being displayed
                   11488:         result    - scalar containing HTML for web form used to switch to
                   11489:                     a different version (or a link to close window, if pop-up).
                   11490:         js        - javascript for processing selection in versions web form
                   11491: 
                   11492: Side Effects: None.
                   11493: 
                   11494: =item previous_display_javascript()
                   11495: 
                   11496: Inputs: 2
                   11497:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11498:                   breadcrumbs etc., are displayed.
                   11499:         current - student's current version number.
                   11500: 
                   11501: Output: 1
                   11502:         js      - javascript for processing selection in versions web form.
                   11503: 
                   11504: Side Effects: None.
                   11505: 
                   11506: =back
                   11507: 
                   11508: =head1 Routines to process bubblesheet data.
                   11509: 
                   11510: =over 4
                   11511: 
1.531     jms      11512: =item scantron_get_correction() : 
                   11513: 
                   11514:    Builds the interface screen to interact with the operator to fix a
                   11515:    specific error condition in a specific scanline
                   11516: 
                   11517:  Arguments:
                   11518:     $r           - Apache request object
                   11519:     $i           - number of the current scanline
                   11520:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  11521:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11522:     $line        - full contents of the current scanline
                   11523:     $error       - error condition, valid values are
                   11524:                    'incorrectCODE', 'duplicateCODE',
                   11525:                    'doublebubble', 'missingbubble',
                   11526:                    'duplicateID', 'incorrectID'
                   11527:     $arg         - extra information needed
                   11528:        For errors:
                   11529:          - duplicateID   - paper number that this studentID was seen before on
                   11530:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11531:                            seen on before
                   11532:          - incorrectCODE - current incorrect CODE 
                   11533:          - doublebubble  - array ref of the bubble lines that have double
                   11534:                            bubble errors
                   11535:          - missingbubble - array ref of the bubble lines that have missing
                   11536:                            bubble errors
                   11537: 
1.691     raeburn  11538:    $randomorder - True if exam folder has randomorder set
                   11539:    $randompick  - True if exam folder has randompick set
                   11540:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11541:                      for current line to question number used for same question
                   11542:                      in "Master Seqence" (as seen by Course Coordinator).
                   11543:    $startline   - Reference to hash where key is question number (0 is first)
                   11544:                   and value is number of first bubble line for current student
                   11545:                   or code-based randompick and/or randomorder.
                   11546: 
                   11547: 
                   11548: 
1.531     jms      11549: =item  scantron_get_maxbubble() : 
                   11550: 
1.582     raeburn  11551:    Arguments:
                   11552:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11553:                       failure to retrieve a navmap object.
                   11554:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11555:        calling routine should trap the error condition and display the warning
                   11556:        found in &navmap_errormsg().
                   11557: 
1.649     raeburn  11558:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11559: 
1.531     jms      11560:    Returns the maximum number of bubble lines that are expected to
                   11561:    occur. Does this by walking the selected sequence rendering the
                   11562:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11563:    for what the current value of the problem counter is.
                   11564: 
                   11565:    Caches the results to $env{'form.scantron_maxbubble'},
                   11566:    $env{'form.scantron.bubble_lines.n'}, 
                   11567:    $env{'form.scantron.first_bubble_line.n'} and
                   11568:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11569:    which are the total number of bubble lines, the number of bubble
1.531     jms      11570:    lines for response n and number of the first bubble line for response n,
                   11571:    and a comma separated list of numbers of bubble lines for sub-questions
                   11572:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11573: 
                   11574: 
                   11575: =item  scantron_validate_missingbubbles() : 
                   11576: 
                   11577:    Validates all scanlines in the selected file to not have any
                   11578:     answers that don't have bubbles that have not been verified
                   11579:     to be bubble free.
                   11580: 
                   11581: =item  scantron_process_students() : 
                   11582: 
1.659     raeburn  11583:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11584: 
                   11585:    The parsed scanline hash is added to %env 
                   11586: 
                   11587:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11588:    foreach resource , with the form data of
                   11589: 
                   11590: 	'submitted'     =>'scantron' 
                   11591: 	'grade_target'  =>'grade',
                   11592: 	'grade_username'=> username of student
                   11593: 	'grade_domain'  => domain of student
                   11594: 	'grade_courseid'=> of course
                   11595: 	'grade_symb'    => symb of resource to grade
                   11596: 
                   11597:     This triggers a grading pass. The problem grading code takes care
                   11598:     of converting the bubbled letter information (now in %env) into a
                   11599:     valid submission.
                   11600: 
                   11601: =item  scantron_upload_scantron_data() :
                   11602: 
1.659     raeburn  11603:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11604: 
                   11605: =item  scantron_upload_scantron_data_save() : 
                   11606: 
                   11607:    Adds a provided bubble information data file to the course if user
1.770     raeburn  11608:    has the correct privileges to do so.
                   11609: 
                   11610: = item scantron_upload_delete() :
                   11611: 
                   11612:    Deletes a previously uploaded bubble information data file, if user
                   11613:    was the one who uploaded the file, and has the privileges to do so.
1.531     jms      11614: 
                   11615: =item  valid_file() :
                   11616: 
                   11617:    Validates that the requested bubble data file exists in the course.
                   11618: 
                   11619: =item  scantron_download_scantron_data() : 
                   11620: 
                   11621:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11622:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11623:    course.
                   11624: 
                   11625: =item  scantron_validate_ID() : 
                   11626: 
                   11627:    Validates all scanlines in the selected file to not have any
1.556     weissno  11628:    invalid or underspecified student/employee IDs
1.531     jms      11629: 
1.582     raeburn  11630: =item navmap_errormsg() :
                   11631: 
                   11632:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11633:    Should be called whenever the request to instantiate a navmap object fails.
                   11634: 
                   11635: =back
1.582     raeburn  11636: 
1.531     jms      11637: =back
                   11638: 
                   11639: =cut

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