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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.761   ! raeburn     4: # $Id: grades.pm,v 1.760 2019/02/23 15:18:33 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.649     raeburn   318:             my $analyze = 
                    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;
                    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;
                    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.720     kruse     425: 
1.268     albertel  426:     } elsif ( $response eq 'organic') {
1.721     bisitz    427:         my $result=&mt('Smile representation: [_1]',
                    428:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  429: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    430: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    431: 	return $result;
1.335     albertel  432:     } elsif ( $response eq 'Task') {
                    433: 	if ( $answer eq 'SUBMITTED') {
                    434: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  435: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  436: 	    return $result;
                    437: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    438: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    439: 			       keys(%{$record}));
                    440: 	    return join('<br />',($version,@matches));
                    441: 			       
                    442: 			       
                    443: 	} else {
                    444: 	    my $result =
                    445: 		'<p>'
                    446: 		.&mt('Overall result: [_1]',
                    447: 		     $record->{$version."resource.$respid.$partid.status"})
                    448: 		.'</p>';
                    449: 	    
                    450: 	    $result .= '<ul>';
                    451: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    452: 			     keys(%{$record}));
                    453: 	    foreach my $grade (sort(@grade)) {
                    454: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    455: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    456: 				     $dim, $record->{$grade}).
                    457: 			  '</li>';
                    458: 	    }
                    459: 	    $result.='</ul>';
                    460: 	    return $result;
                    461: 	}
1.716     bisitz    462:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    463:         # Respect multiple input fields, see Bug #5409
1.440     albertel  464: 	$answer = 
                    465: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    466: 							      $answer);
1.720     kruse     467: 	return $answer;
1.122     ng        468:     }
1.720     kruse     469:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        470: }
                    471: 
                    472: #-- A couple of common js functions
                    473: sub commonJSfunctions {
                    474:     my $request = shift;
1.597     wenzelju  475:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        476:     function radioSelection(radioButton) {
                    477: 	var selection=null;
                    478: 	if (radioButton.length > 1) {
                    479: 	    for (var i=0; i<radioButton.length; i++) {
                    480: 		if (radioButton[i].checked) {
                    481: 		    return radioButton[i].value;
                    482: 		}
                    483: 	    }
                    484: 	} else {
                    485: 	    if (radioButton.checked) return radioButton.value;
                    486: 	}
                    487: 	return selection;
                    488:     }
                    489: 
                    490:     function pullDownSelection(selectOne) {
                    491: 	var selection="";
                    492: 	if (selectOne.length > 1) {
                    493: 	    for (var i=0; i<selectOne.length; i++) {
                    494: 		if (selectOne[i].selected) {
                    495: 		    return selectOne[i].value;
                    496: 		}
                    497: 	    }
                    498: 	} else {
1.138     albertel  499:             // only one value it must be the selected one
                    500: 	    return selectOne.value;
1.118     ng        501: 	}
                    502:     }
                    503: COMMONJSFUNCTIONS
                    504: }
                    505: 
1.44      ng        506: #--- Dumps the class list with usernames,list of sections,
                    507: #--- section, ids and fullnames for each user.
                    508: sub getclasslist {
1.750     raeburn   509:     my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
1.291     albertel  510:     my @getsec;
1.450     banghart  511:     my @getgroup;
1.442     banghart  512:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  513:     if (!ref($getsec)) {
                    514: 	if ($getsec ne '' && $getsec ne 'all') {
                    515: 	    @getsec=($getsec);
                    516: 	}
                    517:     } else {
                    518: 	@getsec=@{$getsec};
                    519:     }
                    520:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  521:     if (!ref($getgroup)) {
                    522: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    523: 	    @getgroup=($getgroup);
                    524: 	}
                    525:     } else {
                    526: 	@getgroup=@{$getgroup};
                    527:     }
                    528:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  529: 
1.449     banghart  530:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  531:     # Bail out if we were unable to get the classlist
1.56      matthew   532:     return if (! defined($classlist));
1.449     banghart  533:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   534:     #
                    535:     my %sections;
                    536:     my %fullnames;
1.750     raeburn   537:     my ($cdom,$cnum,$partlist);
                    538:     if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    539:         $cdom = $env{"course.$env{'request.course.id'}.domain"};
                    540:         $cnum = $env{"course.$env{'request.course.id'}.num"};
                    541:         my $res_error;
                    542:         ($partlist,my $handgrade,my $responseType) = &response_type($symb,\$res_error);
                    543:     }
1.205     matthew   544:     foreach my $student (keys(%$classlist)) {
                    545:         my $end      = 
                    546:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    547:         my $start    = 
                    548:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    549:         my $id       = 
                    550:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    551:         my $section  = 
                    552:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    553:         my $fullname = 
                    554:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    555:         my $status   = 
                    556:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  557:         my $group   = 
                    558:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        559: 	# filter students according to status selected
1.750     raeburn   560: 	if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
1.442     banghart  561: 	    if (!($stu_status =~ $status)) {
1.450     banghart  562: 		delete($classlist->{$student});
1.76      ng        563: 		next;
                    564: 	    }
                    565: 	}
1.450     banghart  566: 	# filter students according to groups selected
1.453     banghart  567: 	my @stu_groups = split(/,/,$group);
1.450     banghart  568: 	if (@getgroup) {
                    569: 	    my $exclude = 1;
1.454     banghart  570: 	    foreach my $grp (@getgroup) {
                    571: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  572: 	            if ($stu_group eq $grp) {
                    573: 	                $exclude = 0;
                    574:     	            } 
1.450     banghart  575: 	        }
1.453     banghart  576:     	        if (($grp eq 'none') && !$group) {
1.750     raeburn   577:         	    $exclude = 0;
1.453     banghart  578:         	}
1.450     banghart  579: 	    }
                    580: 	    if ($exclude) {
                    581: 	        delete($classlist->{$student});
1.750     raeburn   582: 		next;
1.450     banghart  583: 	    }
                    584: 	}
1.750     raeburn   585:         if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
                    586:             my $udom =
                    587:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
                    588:             my $uname =
                    589:                 $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
                    590:             if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
                    591:                 if ($submitonly eq 'queued') {
                    592:                     my %queue_status =
                    593:                         &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    594:                                                                 $udom,$uname);
                    595:                     if (!defined($queue_status{'gradingqueue'})) {
                    596:                         delete($classlist->{$student});
                    597:                         next;
                    598:                     }
                    599:                 } else {
                    600:                     my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
                    601:                     my $submitted = 0;
                    602:                     my $graded = 0;
                    603:                     my $incorrect = 0;
                    604:                     foreach (keys(%status)) {
                    605:                         $submitted = 1 if ($status{$_} ne 'nothing');
                    606:                         $graded = 1 if ($status{$_} =~ /^ungraded/);
                    607:                         $incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    608: 
                    609:                         my ($foo,$partid,$foo1) = split(/\./,$_);
                    610:                         if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                    611:                             $submitted = 0;
                    612:                         }
                    613:                     }
                    614:                     if (!$submitted && ($submitonly eq 'yes' ||
                    615:                                         $submitonly eq 'incorrect' ||
                    616:                                         $submitonly eq 'graded')) {
                    617:                         delete($classlist->{$student});
                    618:                         next;
                    619:                     } elsif (!$graded && ($submitonly eq 'graded')) {
                    620:                         delete($classlist->{$student});
                    621:                         next;
                    622:                     } elsif (!$incorrect && $submitonly eq 'incorrect') {
                    623:                         delete($classlist->{$student});
                    624:                         next;
                    625:                     }
                    626:                 }
                    627:             }
                    628:         }
1.205     matthew   629: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  630: 	if (&canview($section)) {
1.291     albertel  631: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  632: 		$sections{$section}++;
1.450     banghart  633: 		if ($classlist->{$student}) {
                    634: 		    $fullnames{$student}=$fullname;
                    635: 		}
1.103     albertel  636: 	    } else {
1.205     matthew   637: 		delete($classlist->{$student});
1.103     albertel  638: 	    }
                    639: 	} else {
1.205     matthew   640: 	    delete($classlist->{$student});
1.103     albertel  641: 	}
1.44      ng        642:     }
1.56      matthew   643:     my @sections = sort(keys(%sections));
                    644:     return ($classlist,\@sections,\%fullnames);
1.44      ng        645: }
                    646: 
1.103     albertel  647: sub canmodify {
                    648:     my ($sec)=@_;
                    649:     if ($perm{'mgr'}) {
                    650: 	if (!defined($perm{'mgr_section'})) {
                    651: 	    # can modify whole class
                    652: 	    return 1;
                    653: 	} else {
                    654: 	    if ($sec eq $perm{'mgr_section'}) {
                    655: 		#can modify the requested section
                    656: 		return 1;
                    657: 	    } else {
                    658: 		# can't modify the request section
                    659: 		return 0;
                    660: 	    }
                    661: 	}
                    662:     }
                    663:     #can't modify
                    664:     return 0;
                    665: }
                    666: 
                    667: sub canview {
                    668:     my ($sec)=@_;
                    669:     if ($perm{'vgr'}) {
                    670: 	if (!defined($perm{'vgr_section'})) {
                    671: 	    # can modify whole class
                    672: 	    return 1;
                    673: 	} else {
                    674: 	    if ($sec eq $perm{'vgr_section'}) {
                    675: 		#can modify the requested section
                    676: 		return 1;
                    677: 	    } else {
                    678: 		# can't modify the request section
                    679: 		return 0;
                    680: 	    }
                    681: 	}
                    682:     }
                    683:     #can't modify
                    684:     return 0;
                    685: }
                    686: 
1.44      ng        687: #--- Retrieve the grade status of a student for all the parts
                    688: sub student_gradeStatus {
1.324     albertel  689:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  690:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        691:     my %partstatus = ();
                    692:     foreach (@$partlist) {
1.128     ng        693: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        694: 	$status              = 'nothing' if ($status eq '');
                    695: 	$partstatus{$_}      = $status;
                    696: 	my $subkey           = "resource.$_.submitted_by";
                    697: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    698:     }
                    699:     return %partstatus;
                    700: }
                    701: 
1.45      ng        702: # hidden form and javascript that calls the form
                    703: # Use by verifyscript and viewgrades
                    704: # Shows a student's view of problem and submission
                    705: sub jscriptNform {
1.324     albertel  706:     my ($symb) = @_;
1.442     banghart  707:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  708:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        709: 	'    function viewOneStudent(user,domain) {'."\n".
                    710: 	'	document.onestudent.student.value = user;'."\n".
                    711: 	'	document.onestudent.userdom.value = domain;'."\n".
                    712: 	'	document.onestudent.submit();'."\n".
                    713: 	'    }'."\n".
1.597     wenzelju  714: 	"\n");
1.45      ng        715:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  716: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  717: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        718: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    719: 	'<input type="hidden" name="student" value="" />'."\n".
                    720: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    721: 	'</form>'."\n";
                    722:     return $jscript;
                    723: }
1.39      ng        724: 
1.447     foxr      725: 
                    726: 
1.315     bowersj2  727: # Given the score (as a number [0-1] and the weight) what is the final
                    728: # point value? This function will round to the nearest tenth, third,
                    729: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  730: sub compute_points {
1.315     bowersj2  731:     my ($score, $weight) = @_;
                    732:     
                    733:     my $tolerance = .00001;
                    734:     my $points = $score * $weight;
                    735: 
                    736:     # Check for nearness to 1/x.
                    737:     my $check_for_nearness = sub {
                    738:         my ($factor) = @_;
                    739:         my $num = ($points * $factor) + $tolerance;
                    740:         my $floored_num = floor($num);
1.316     albertel  741:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  742:             return $floored_num / $factor;
                    743:         }
                    744:         return $points;
                    745:     };
                    746: 
                    747:     $points = $check_for_nearness->(10);
                    748:     $points = $check_for_nearness->(3);
                    749:     $points = $check_for_nearness->(4);
                    750:     
                    751:     return $points;
                    752: }
                    753: 
1.44      ng        754: #------------------ End of general use routines --------------------
1.87      www       755: 
                    756: #
                    757: # Find most similar essay
                    758: #
                    759: 
                    760: sub most_similar {
1.674     raeburn   761:     my ($uname,$udom,$symb,$uessay)=@_;
                    762: 
                    763:     unless ($symb) { return ''; }
                    764: 
                    765:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       766: 
                    767: # ignore spaces and punctuation
                    768: 
                    769:     $uessay=~s/\W+/ /gs;
                    770: 
1.282     www       771: # ignore empty submissions (occuring when only files are sent)
                    772: 
1.598     www       773:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       774: 
1.87      www       775: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       776:     my $limit=0.6;
1.87      www       777:     my $sname='';
                    778:     my $sdom='';
                    779:     my $scrsid='';
                    780:     my $sessay='';
                    781: # go through all essays ...
1.674     raeburn   782:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  783: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       784: # ... except the same student
1.426     albertel  785:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   786: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  787: 	$tessay=~s/\W+/ /gs;
1.87      www       788: # String similarity gives up if not even limit
1.426     albertel  789: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       790: # Found one
1.426     albertel  791: 	if ($tsimilar>$limit) {
                    792: 	    $limit=$tsimilar;
                    793: 	    $sname=$tname;
                    794: 	    $sdom=$tdom;
                    795: 	    $scrsid=$tcrsid;
1.674     raeburn   796: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  797: 	}
1.87      www       798:     }
1.88      www       799:     if ($limit>0.6) {
1.87      www       800:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    801:     } else {
                    802:        return ('','','','',0);
                    803:     }
                    804: }
                    805: 
1.44      ng        806: #-------------------------------------------------------------------
                    807: 
                    808: #------------------------------------ Receipt Verification Routines
1.45      ng        809: #
1.602     www       810: 
                    811: sub initialverifyreceipt {
1.608     www       812:    my ($request,$symb) = @_;
1.602     www       813:    &commonJSfunctions($request);
1.694     bisitz    814:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       815:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    816:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       817:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    818:         '<input type="hidden" name="command" value="verify" />'.
                    819:         "</form>\n";
1.602     www       820: }
                    821: 
1.44      ng        822: #--- Check whether a receipt number is valid.---
                    823: sub verifyreceipt {
1.608     www       824:     my ($request,$symb)  = @_;
1.44      ng        825: 
1.257     albertel  826:     my $courseid = $env{'request.course.id'};
1.184     www       827:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  828: 	$env{'form.receipt'};
1.44      ng        829:     $receipt     =~ s/[^\-\d]//g;
                    830: 
1.487     albertel  831:     my $title.=
                    832: 	'<h3><span class="LC_info">'.
1.605     www       833: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    834: 	'</span></h3>'."\n";
1.44      ng        835: 
                    836:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   837:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  838:     
                    839:     my $receiptparts=0;
1.390     albertel  840:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    841: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  842:     my $parts=['0'];
1.582     raeburn   843:     if ($receiptparts) {
                    844:         my $res_error; 
                    845:         ($parts)=&response_type($symb,\$res_error);
                    846:         if ($res_error) {
                    847:             return &navmap_errormsg();
                    848:         } 
                    849:     }
1.486     albertel  850:     
                    851:     my $header = 
                    852: 	&Apache::loncommon::start_data_table().
                    853: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  854: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    855: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    856: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  857:     if ($receiptparts) {
1.487     albertel  858: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  859:     }
                    860:     $header.=
                    861: 	&Apache::loncommon::end_data_table_header_row();
                    862: 
1.294     albertel  863:     foreach (sort 
                    864: 	     {
                    865: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    866: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    867: 		 }
                    868: 		 return $a cmp $b;
                    869: 	     } (keys(%$fullname))) {
1.44      ng        870: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  871: 	foreach my $part (@$parts) {
                    872: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  873: 		$contents.=
                    874: 		    &Apache::loncommon::start_data_table_row().
                    875: 		    '<td>&nbsp;'."\n".
1.177     albertel  876: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  877: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  878: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    879: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    880: 		if ($receiptparts) {
                    881: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    882: 		}
1.486     albertel  883: 		$contents.= 
                    884: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  885: 		
                    886: 		$matches++;
                    887: 	    }
1.44      ng        888: 	}
                    889:     }
                    890:     if ($matches == 0) {
1.584     bisitz    891:         $string = $title
                    892:                  .'<p class="LC_warning">'
                    893:                  .&mt('No match found for the above receipt number.')
                    894:                  .'</p>';
1.44      ng        895:     } else {
1.324     albertel  896: 	$string = &jscriptNform($symb).$title.
1.487     albertel  897: 	    '<p>'.
1.584     bisitz    898: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  899: 	    '</p>'.
1.486     albertel  900: 	    $header.
                    901: 	    $contents.
                    902: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        903:     }
1.614     www       904:     return $string;
1.44      ng        905: }
                    906: 
                    907: #--- This is called by a number of programs.
                    908: #--- Called from the Grading Menu - View/Grade an individual student
                    909: #--- Also called directly when one clicks on the subm button 
                    910: #    on the problem page.
1.30      ng        911: sub listStudents {
1.617     www       912:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  913: 
1.747     raeburn   914:     my $is_tool   = ($symb =~ /ext\.tool$/);
1.257     albertel  915:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    916:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    917:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  918:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       919:     unless ($submitonly) {
                    920:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    921:     }
1.49      albertel  922: 
1.632     www       923:     my $result='';
1.623     www       924:     my $res_error;
                    925:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  926: 
1.736     damieng   927:     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   928: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    929: 		'single'   => 'Please select the student before clicking on the Next button.',
                    930: 	     );
1.736     damieng   931:     &js_escape(\%js_lt);
1.597     wenzelju  932:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        933:     function checkSelect(checkBox) {
                    934: 	var ctr=0;
                    935: 	var sense="";
                    936: 	if (checkBox.length > 1) {
                    937: 	    for (var i=0; i<checkBox.length; i++) {
                    938: 		if (checkBox[i].checked) {
                    939: 		    ctr++;
                    940: 		}
                    941: 	    }
1.736     damieng   942: 	    sense = '$js_lt{'multiple'}';
1.110     ng        943: 	} else {
                    944: 	    if (checkBox.checked) {
                    945: 		ctr = 1;
                    946: 	    }
1.736     damieng   947: 	    sense = '$js_lt{'single'}';
1.110     ng        948: 	}
                    949: 	if (ctr == 0) {
1.485     albertel  950: 	    alert(sense);
1.110     ng        951: 	    return false;
                    952: 	}
                    953: 	document.gradesub.submit();
                    954:     }
                    955: 
                    956:     function reLoadList(formname) {
1.112     ng        957: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        958: 	formname.command.value = 'submission';
                    959: 	formname.submit();
                    960:     }
1.45      ng        961: LISTJAVASCRIPT
                    962: 
1.118     ng        963:     &commonJSfunctions($request);
1.41      ng        964:     $request->print($result);
1.39      ng        965: 
1.154     albertel  966:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       967: 	"\n";
1.485     albertel  968: 	
1.561     bisitz    969:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
1.745     raeburn   970:     unless ($is_tool) {
                    971:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    972:                       .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    973:                       .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    974:                       .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    975:                       .&Apache::lonhtmlcommon::row_closure();
                    976:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    977:                       .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    978:                       .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    979:                       .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    980:                       .&Apache::lonhtmlcommon::row_closure();
                    981:     }
1.485     albertel  982: 
                    983:     my $submission_options;
1.442     banghart  984:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    985:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  986:     $env{'form.Status'} = $saveStatus;
1.745     raeburn   987:     my %optiontext;
                    988:     if ($is_tool) {
                    989:         %optiontext = &Apache::lonlocal::texthash (
                    990:                           lastonly => 'last transaction',
                    991:                           last     => 'last transaction with details',
                    992:                           datesub  => 'all transactions',
                    993:                           all      => 'all transactions with details',
                    994:                       );
                    995:     } else {
                    996:         %optiontext = &Apache::lonlocal::texthash (
                    997:                           lastonly => 'last submission',
                    998:                           last     => 'last submission with details',
                    999:                           datesub  => 'all submissions',
                   1000:                           all      => 'all submissions with details',
                   1001:                       );
                   1002:     }
1.485     albertel 1003:     $submission_options.=
1.592     bisitz   1004:         '<span class="LC_nobreak">'.
1.624     www      1005:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.745     raeburn  1006:         $optiontext{'lastonly'}.' </label></span>'."\n".
1.592     bisitz   1007:         '<span class="LC_nobreak">'.
                   1008:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.745     raeburn  1009:         $optiontext{'last'}.' </label></span>'."\n".
1.592     bisitz   1010:         '<span class="LC_nobreak">'.
1.628     www      1011:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.745     raeburn  1012:         $optiontext{'datesub'}.'</label></span>'."\n".
1.592     bisitz   1013:         '<span class="LC_nobreak">'.
                   1014:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.745     raeburn  1015:         $optiontext{'all'}.'</label></span>';
                   1016:     my $viewtitle;
                   1017:     if ($is_tool) {
                   1018:         $viewtitle = &mt('View Transactions');
                   1019:     } else {
                   1020:         $viewtitle = &mt('View Submissions');
                   1021:     }
                   1022:     $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1.561     bisitz   1023:                   .$submission_options
                   1024:                   .&Apache::lonhtmlcommon::row_closure();
                   1025: 
1.745     raeburn  1026:     my $closure;
                   1027:     if (($is_tool) && (exists($env{'form.Status'}))) {
                   1028:         $closure = 1;
                   1029:     }
1.561     bisitz   1030:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1031:                   .'<select name="increment">'
                   1032:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1033:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1034:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1035:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                   1036:                   .'</select>'
1.745     raeburn  1037:                   .&Apache::lonhtmlcommon::row_closure($closure);
1.485     albertel 1038: 
                   1039:     $gradeTable .= 
1.432     banghart 1040:         &build_section_inputs().
1.45      ng       1041: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel 1042: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1043: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1044: 
1.618     www      1045:     if (exists($env{'form.Status'})) {
1.561     bisitz   1046: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1047:     } else {
1.745     raeburn  1048:         if ($is_tool) {
                   1049:             $closure = 1;
                   1050:         }
1.561     bisitz   1051:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1052:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1053:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
1.745     raeburn  1054:                       .&Apache::lonhtmlcommon::row_closure($closure);
1.124     ng       1055:     }
1.112     ng       1056: 
1.745     raeburn  1057:     unless ($is_tool) {
                   1058:         $closure = 1;
                   1059:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1060:                       .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1061:                       .&Apache::lonhtmlcommon::row_closure($closure);
                   1062:     }
                   1063:     $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
                   1064:     my $regrademsg;
                   1065:     if ($is_tool) {
                   1066:         $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.");
                   1067:     } else {
                   1068:         $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.");
                   1069:     }
1.561     bisitz   1070:     $gradeTable .= '<p>'
1.745     raeburn  1071:                   .$regrademsg."\n"
1.561     bisitz   1072:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1073:                   .'</p>';
1.249     albertel 1074: 
                   1075: # checkall buttons
                   1076:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1077:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1078:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1079:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1080:     $gradeTable.=&check_buttons();
1.450     banghart 1081:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1082:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1083: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1084:     my $loop = 0;
                   1085:     while ($loop < 2) {
1.485     albertel 1086: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1087: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www      1088: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel 1089: 	    foreach my $part (sort(@$partlist)) {
                   1090: 		my $display_part=
                   1091: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1092: 		$gradeTable.=
                   1093: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1094: 	    }
1.301     albertel 1095: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1096: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1097: 	}
                   1098: 	$loop++;
1.126     ng       1099: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1100:     }
1.474     albertel 1101:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1102: 
1.45      ng       1103:     my $ctr = 0;
1.294     albertel 1104:     foreach my $student (sort 
                   1105: 			 {
                   1106: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1107: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1108: 			     }
                   1109: 			     return $a cmp $b;
                   1110: 			 }
                   1111: 			 (keys(%$fullname))) {
1.41      ng       1112: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1113: 
1.110     ng       1114: 	my %status = ();
1.301     albertel 1115: 
                   1116: 	if ($submitonly eq 'queued') {
                   1117: 	    my %queue_status = 
                   1118: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1119: 							$udom,$uname);
                   1120: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1121: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1122: 	}
                   1123: 
1.618     www      1124: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1125: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1126: 	    my $submitted = 0;
1.164     albertel 1127: 	    my $graded = 0;
1.248     albertel 1128: 	    my $incorrect = 0;
1.110     ng       1129: 	    foreach (keys(%status)) {
1.145     albertel 1130: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1131: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1132: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1133: 		
1.110     ng       1134: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1135: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1136: 		    $submitted = 0;
1.150     albertel 1137: 		    my ($part)=split(/\./,$partid);
1.110     ng       1138: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1139: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1140: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1141: 		}
1.41      ng       1142: 	    }
1.248     albertel 1143: 	    
1.156     albertel 1144: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1145: 				     $submitonly eq 'incorrect' ||
                   1146: 				     $submitonly eq 'graded'));
1.248     albertel 1147: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1148: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1149: 	}
1.34      ng       1150: 
1.45      ng       1151: 	$ctr++;
1.249     albertel 1152: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1153:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1154: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1155: 	    if ($ctr%2 ==1) {
                   1156: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1157: 	    }
1.126     ng       1158: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1159:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1160:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1161: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1162: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1163: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1164: 
1.618     www      1165: 	    if ($submitonly ne 'all') {
1.524     raeburn  1166: 		foreach (sort(keys(%status))) {
1.485     albertel 1167: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1168: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1169: 		}
1.41      ng       1170: 	    }
1.126     ng       1171: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1172: 	    if ($ctr%2 ==0) {
                   1173: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1174: 	    }
1.41      ng       1175: 	}
                   1176:     }
1.110     ng       1177:     if ($ctr%2 ==1) {
1.126     ng       1178: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1179: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1180: 		foreach (@$partlist) {
                   1181: 		    $gradeTable.='<td>&nbsp;</td>';
                   1182: 		}
1.301     albertel 1183: 	    } elsif ($submitonly eq 'queued') {
                   1184: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1185: 	    }
1.474     albertel 1186: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1187:     }
                   1188: 
1.474     albertel 1189:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1190:         '<input type="button" '.
                   1191:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1192:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1193:     if ($ctr == 0) {
1.96      albertel 1194: 	my $num_students=(scalar(keys(%$fullname)));
                   1195: 	if ($num_students eq 0) {
1.485     albertel 1196: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1197: 	} else {
1.171     albertel 1198: 	    my $submissions='submissions';
                   1199: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1200: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1201: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1202: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1203: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1204: 		    $num_students).
                   1205: 		'</span><br />';
1.96      albertel 1206: 	}
1.46      ng       1207:     } elsif ($ctr == 1) {
1.474     albertel 1208: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1209:     }
                   1210:     $request->print($gradeTable);
1.44      ng       1211:     return '';
1.10      ng       1212: }
                   1213: 
1.44      ng       1214: #---- Called from the listStudents routine
1.249     albertel 1215: 
                   1216: sub check_script {
                   1217:     my ($form, $type)=@_;
1.597     wenzelju 1218:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1219:     function checkall() {
                   1220:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1221:             ele = document.forms.'.$form.'.elements[i];
                   1222:             if (ele.name == "'.$type.'") {
                   1223:             document.forms.'.$form.'.elements[i].checked=true;
                   1224:                                        }
                   1225:         }
                   1226:     }
                   1227: 
                   1228:     function checksec() {
                   1229:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1230:             ele = document.forms.'.$form.'.elements[i];
                   1231:            string = document.forms.'.$form.'.chksec.value;
                   1232:            if
                   1233:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1234:               document.forms.'.$form.'.elements[i].checked=true;
                   1235:             }
                   1236:         }
                   1237:     }
                   1238: 
                   1239: 
                   1240:     function uncheckall() {
                   1241:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1242:             ele = document.forms.'.$form.'.elements[i];
                   1243:             if (ele.name == "'.$type.'") {
                   1244:             document.forms.'.$form.'.elements[i].checked=false;
                   1245:                                        }
                   1246:         }
                   1247:     }
                   1248: 
1.597     wenzelju 1249: '."\n");
1.249     albertel 1250:     return $chkallscript;
                   1251: }
                   1252: 
                   1253: sub check_buttons {
1.485     albertel 1254:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1255:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1256:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1257:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1258:     return $buttons;
                   1259: }
                   1260: 
1.44      ng       1261: #     Displays the submissions for one student or a group of students
1.34      ng       1262: sub processGroup {
1.619     www      1263:     my ($request,$symb)  = @_;
1.41      ng       1264:     my $ctr        = 0;
1.155     albertel 1265:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1266:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1267: 
1.396     banghart 1268:     foreach my $student (@stuchecked) {
                   1269: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1270: 	$env{'form.student'}        = $uname;
                   1271: 	$env{'form.userdom'}        = $udom;
                   1272: 	$env{'form.fullname'}       = $fullname;
1.619     www      1273: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1274: 	$ctr++;
                   1275:     }
                   1276:     return '';
1.35      ng       1277: }
1.34      ng       1278: 
1.44      ng       1279: #------------------------------------------------------------------------------------
                   1280: #
                   1281: #-------------------------- Next few routines handles grading by student, essentially
                   1282: #                           handles essay response type problem/part
                   1283: #
                   1284: #--- Javascript to handle the submission page functionality ---
                   1285: sub sub_page_js {
                   1286:     my $request = shift;
1.736     damieng  1287:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
                   1288:     &js_escape(\$alertmsg);
1.597     wenzelju 1289:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1290:     function updateRadio(formname,id,weight) {
1.125     ng       1291: 	var gradeBox = formname["GD_BOX"+id];
                   1292: 	var radioButton = formname["RADVAL"+id];
                   1293: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1294: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1295: 	gradeBox.value = pts;
                   1296: 	var resetbox = false;
                   1297: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1298: 	    alert("$alertmsg"+pts);
1.71      ng       1299: 	    for (var i=0; i<radioButton.length; i++) {
                   1300: 		if (radioButton[i].checked) {
                   1301: 		    gradeBox.value = i;
                   1302: 		    resetbox = true;
                   1303: 		}
                   1304: 	    }
                   1305: 	    if (!resetbox) {
                   1306: 		formtextbox.value = "";
                   1307: 	    }
                   1308: 	    return;
1.44      ng       1309: 	}
1.71      ng       1310: 
                   1311: 	if (pts > weight) {
                   1312: 	    var resp = confirm("You entered a value ("+pts+
                   1313: 			       ") greater than the weight for the part. Accept?");
                   1314: 	    if (resp == false) {
1.125     ng       1315: 		gradeBox.value = oldpts;
1.71      ng       1316: 		return;
                   1317: 	    }
1.44      ng       1318: 	}
1.13      albertel 1319: 
1.71      ng       1320: 	for (var i=0; i<radioButton.length; i++) {
                   1321: 	    radioButton[i].checked=false;
                   1322: 	    if (pts == i && pts != "") {
                   1323: 		radioButton[i].checked=true;
                   1324: 	    }
                   1325: 	}
                   1326: 	updateSelect(formname,id);
1.125     ng       1327: 	formname["stores"+id].value = "0";
1.41      ng       1328:     }
1.5       albertel 1329: 
1.72      ng       1330:     function writeBox(formname,id,pts) {
1.125     ng       1331: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1332: 	if (checkSolved(formname,id) == 'update') {
                   1333: 	    gradeBox.value = pts;
                   1334: 	} else {
1.125     ng       1335: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1336: 	    gradeBox.value = oldpts;
1.125     ng       1337: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1338: 	    for (var i=0; i<radioButton.length; i++) {
                   1339: 		radioButton[i].checked=false;
1.72      ng       1340: 		if (i == oldpts) {
1.71      ng       1341: 		    radioButton[i].checked=true;
                   1342: 		}
                   1343: 	    }
1.41      ng       1344: 	}
1.125     ng       1345: 	formname["stores"+id].value = "0";
1.71      ng       1346: 	updateSelect(formname,id);
                   1347: 	return;
1.41      ng       1348:     }
1.44      ng       1349: 
1.71      ng       1350:     function clearRadBox(formname,id) {
                   1351: 	if (checkSolved(formname,id) == 'noupdate') {
                   1352: 	    updateSelect(formname,id);
                   1353: 	    return;
                   1354: 	}
1.125     ng       1355: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1356: 	for (var i=0; i<gradeSelect.length; i++) {
                   1357: 	    if (gradeSelect[i].selected) {
                   1358: 		var selectx=i;
                   1359: 	    }
                   1360: 	}
1.125     ng       1361: 	var stores = formname["stores"+id];
1.71      ng       1362: 	if (selectx == stores.value) { return };
1.125     ng       1363: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1364: 	gradeBox.value = "";
1.125     ng       1365: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1366: 	for (var i=0; i<radioButton.length; i++) {
                   1367: 	    radioButton[i].checked=false;
                   1368: 	}
                   1369: 	stores.value = selectx;
                   1370:     }
1.5       albertel 1371: 
1.71      ng       1372:     function checkSolved(formname,id) {
1.125     ng       1373: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1374: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1375: 	    if (!reply) {return "noupdate";}
1.120     ng       1376: 	    formname.overRideScore.value = 'yes';
1.41      ng       1377: 	}
1.71      ng       1378: 	return "update";
1.13      albertel 1379:     }
1.71      ng       1380: 
                   1381:     function updateSelect(formname,id) {
1.125     ng       1382: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1383: 	return;
1.41      ng       1384:     }
1.33      ng       1385: 
1.121     ng       1386: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1387:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1388: 	formname.gradeOpt.value = val;
1.71      ng       1389: 	if (val == "Save & Next") {
                   1390: 	    for (i=0;i<=total;i++) {
                   1391: 		for (j=0;j<parttot;j++) {
1.125     ng       1392: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1393: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1394: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1395: 			if (points == "") {
1.125     ng       1396: 			    var name = formname["name"+i].value;
1.129     ng       1397: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1398: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1399: 					       ", part "+partid+". Continue?");
1.71      ng       1400: 			    if (resp == false) {
1.125     ng       1401: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1402: 				return false;
                   1403: 			    }
                   1404: 			}
                   1405: 		    }
                   1406: 		}
                   1407: 	    }
                   1408: 	}
1.120     ng       1409: 	formname.submit();
                   1410:     }
                   1411: 
1.71      ng       1412: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1413:     function checkSubmitPage(formname,total) {
                   1414: 	noscore = new Array(100);
                   1415: 	var ptr = 0;
                   1416: 	for (i=1;i<total;i++) {
1.125     ng       1417: 	    var partid = formname["q_"+i].value;
1.127     ng       1418: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1419: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1420: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1421: 		if (points == "" && status != "correct_by_student") {
                   1422: 		    noscore[ptr] = i;
                   1423: 		    ptr++;
                   1424: 		}
                   1425: 	    }
                   1426: 	}
                   1427: 	if (ptr != 0) {
                   1428: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1429: 	    var prolist = "";
                   1430: 	    if (ptr == 1) {
                   1431: 		prolist = noscore[0];
                   1432: 	    } else {
                   1433: 		var i = 0;
                   1434: 		while (i < ptr-1) {
                   1435: 		    prolist += noscore[i]+", ";
                   1436: 		    i++;
                   1437: 		}
                   1438: 		prolist += "and "+noscore[i];
                   1439: 	    }
                   1440: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1441: 	    if (resp == false) {
                   1442: 		return false;
                   1443: 	    }
                   1444: 	}
1.45      ng       1445: 
1.71      ng       1446: 	formname.submit();
                   1447:     }
                   1448: SUBJAVASCRIPT
                   1449: }
1.45      ng       1450: 
1.71      ng       1451: #--- javascript for essay type problem --
                   1452: sub sub_page_kw_js {
                   1453:     my $request = shift;
1.80      ng       1454:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1455:     &commonJSfunctions($request);
1.350     albertel 1456: 
1.629     www      1457:     my $inner_js_msg_central= (<<INNERJS);
                   1458: <script type="text/javascript">
1.350     albertel 1459:     function checkInput() {
                   1460:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1461:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1462:       var usrctr = document.msgcenter.usrctr.value;
                   1463:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1464:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1465: 
                   1466:       var msgchk = "";
                   1467:       if (document.msgcenter.subchk.checked) {
                   1468:          msgchk = "msgsub,";
                   1469:       }
                   1470:       var includemsg = 0;
                   1471:       for (var i=1; i<=nmsg; i++) {
                   1472:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1473:           var frmmsg = document.msgcenter["msg"+i];
                   1474:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1475:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1476:           showflg.value = "1";
                   1477:           var chkbox = document.msgcenter["msgn"+i];
                   1478:           if (chkbox.checked) {
                   1479:              msgchk += "savemsg"+i+",";
                   1480:              includemsg = 1;
                   1481:           }
                   1482:       }
                   1483:       if (document.msgcenter.newmsgchk.checked) {
                   1484:          msgchk += "newmsg"+usrctr;
                   1485:          includemsg = 1;
                   1486:       }
                   1487:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1488:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1489:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1490:       includemsg.value = msgchk;
                   1491: 
                   1492:       self.close()
                   1493: 
                   1494:     }
1.629     www      1495: </script>
1.350     albertel 1496: INNERJS
                   1497: 
1.629     www      1498:     my $inner_js_highlight_central= (<<INNERJS);
                   1499: <script type="text/javascript">
1.351     albertel 1500:     function updateChoice(flag) {
                   1501:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1502:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1503:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1504:       opener.document.SCORE.refresh.value = "on";
                   1505:       if (opener.document.SCORE.keywords.value!=""){
                   1506:          opener.document.SCORE.submit();
                   1507:       }
                   1508:       self.close()
                   1509:     }
1.629     www      1510: </script>
1.351     albertel 1511: INNERJS
                   1512: 
                   1513:     my $start_page_msg_central = 
                   1514:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1515: 				       {'js_ready'  => 1,
                   1516: 					'only_body' => 1,
                   1517: 					'bgcolor'   =>'#FFFFFF',});
                   1518:     my $end_page_msg_central = 
                   1519: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1520: 
                   1521: 
                   1522:     my $start_page_highlight_central = 
                   1523:         &Apache::loncommon::start_page('Highlight Central',
                   1524: 				       $inner_js_highlight_central,
1.350     albertel 1525: 				       {'js_ready'  => 1,
                   1526: 					'only_body' => 1,
                   1527: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1528:     my $end_page_highlight_central = 
1.350     albertel 1529: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1530: 
1.219     www      1531:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1532:     $docopen=~s/^document\.//;
1.736     damieng  1533:     my %js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1534:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1535:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1536:                 adds => 'Add selection to keyword list? Edit if desired.',
1.736     damieng  1537:                 col1 => 'red',
                   1538:                 col2 => 'green',
                   1539:                 col3 => 'blue',
                   1540:                 siz1 => 'normal',
                   1541:                 siz2 => '+1',
                   1542:                 siz3 => '+2',
                   1543:                 sty1 => 'normal',
                   1544:                 sty2 => 'italic',
                   1545:                 sty3 => 'bold',
                   1546:              );
                   1547:     my %html_js_lt = &Apache::lonlocal::texthash(
1.652     raeburn  1548:                 comp => 'Compose Message for: ',
                   1549:                 incl => 'Include',
1.656     raeburn  1550:                 type => 'Type',
1.652     raeburn  1551:                 subj => 'Subject',
                   1552:                 mesa => 'Message',
                   1553:                 new  => 'New',
                   1554:                 save => 'Save',
                   1555:                 canc => 'Cancel',
                   1556:                 kehi => 'Keyword Highlight Options',
                   1557:                 txtc => 'Text Color',
                   1558:                 font => 'Font Size',
1.656     raeburn  1559:                 fnst => 'Font Style',
1.652     raeburn  1560:              );
1.736     damieng  1561:     &js_escape(\%js_lt);
                   1562:     &html_escape(\%html_js_lt);
                   1563:     &js_escape(\%html_js_lt);
1.597     wenzelju 1564:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1565: 
1.44      ng       1566: //===================== Show list of keywords ====================
1.122     ng       1567:   function keywords(formname) {
1.736     damieng  1568:     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1569:     if (nret==null) return;
1.122     ng       1570:     formname.keywords.value = nret;
1.44      ng       1571: 
1.122     ng       1572:     if (formname.keywords.value != "") {
1.128     ng       1573: 	formname.refresh.value = "on";
1.122     ng       1574: 	formname.submit();
1.44      ng       1575:     }
                   1576:     return;
                   1577:   }
                   1578: 
                   1579: //===================== Script to view submitted by ==================
                   1580:   function viewSubmitter(submitter) {
                   1581:     document.SCORE.refresh.value = "on";
                   1582:     document.SCORE.NCT.value = "1";
                   1583:     document.SCORE.unamedom0.value = submitter;
                   1584:     document.SCORE.submit();
                   1585:     return;
                   1586:   }
                   1587: 
                   1588: //===================== Script to add keyword(s) ==================
                   1589:   function getSel() {
                   1590:     if (document.getSelection) txt = document.getSelection();
                   1591:     else if (document.selection) txt = document.selection.createRange().text;
                   1592:     else return;
                   1593:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1594:     if (cleantxt=="") {
1.736     damieng  1595: 	alert("$js_lt{'plse'}");
1.44      ng       1596: 	return;
                   1597:     }
1.736     damieng  1598:     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1599:     if (nret==null) return;
1.127     ng       1600:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1601:     if (document.SCORE.keywords.value != "") {
1.127     ng       1602: 	document.SCORE.refresh.value = "on";
1.44      ng       1603: 	document.SCORE.submit();
                   1604:     }
                   1605:     return;
                   1606:   }
                   1607: 
                   1608: //====================== Script for composing message ==============
1.80      ng       1609:    // preload images
                   1610:    img1 = new Image();
                   1611:    img1.src = "$iconpath/mailbkgrd.gif";
                   1612:    img2 = new Image();
                   1613:    img2.src = "$iconpath/mailto.gif";
                   1614: 
1.44      ng       1615:   function msgCenter(msgform,usrctr,fullname) {
                   1616:     var Nmsg  = msgform.savemsgN.value;
                   1617:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1618:     var subject = msgform.msgsub.value;
1.127     ng       1619:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1620:     re = /msgsub/;
                   1621:     var shwsel = "";
                   1622:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1623:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1624:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1625:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1626: 	var testmsg = "savemsg"+i+",";
                   1627: 	re = new RegExp(testmsg,"g");
1.44      ng       1628: 	shwsel = "";
                   1629: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1630: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1631: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1632: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1633: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1634:     }
1.125     ng       1635:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1636:     shwsel = "";
                   1637:     re = /newmsg/;
                   1638:     if (re.test(msgchk)) { shwsel = "checked" }
                   1639:     newMsg(newmsg,shwsel);
                   1640:     msgTail(); 
                   1641:     return;
                   1642:   }
                   1643: 
1.123     ng       1644:   function checkEntities(strx) {
                   1645:     if (strx.length == 0) return strx;
                   1646:     var orgStr = ["&", "<", ">", '"']; 
                   1647:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1648:     var counter = 0;
                   1649:     while (counter < 4) {
                   1650: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1651: 	counter++;
                   1652:     }
                   1653:     return strx;
                   1654:   }
                   1655: 
                   1656:   function strReplace(strx, orgStr, newStr) {
                   1657:     return strx.split(orgStr).join(newStr);
                   1658:   }
                   1659: 
1.44      ng       1660:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1661:     var height = 70*Nmsg+250;
1.44      ng       1662:     if (height > 600) {
                   1663: 	height = 600;
                   1664:     }
1.118     ng       1665:     var xpos = (screen.width-600)/2;
                   1666:     xpos = (xpos < 0) ? '0' : xpos;
                   1667:     var ypos = (screen.height-height)/2-30;
                   1668:     ypos = (ypos < 0) ? '0' : ypos;
                   1669: 
1.668     www      1670:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1671:     pWin.focus();
                   1672:     pDoc = pWin.document;
1.219     www      1673:     pDoc.$docopen;
1.351     albertel 1674:     pDoc.write('$start_page_msg_central');
1.76      ng       1675: 
                   1676:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1677:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.736     damieng  1678:     pDoc.write("<h1>&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1679: 
1.676     golterma 1680:     pDoc.write('<table style="border:1px solid black;"><tr>');
1.736     damieng  1681:     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       1682: }
                   1683:     function displaySubject(msg,shwsel) {
1.76      ng       1684:     pDoc = pWin.document;
1.676     golterma 1685:     pDoc.write("<tr>");
                   1686:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1687:     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.676     golterma 1688:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1689: }
                   1690: 
1.72      ng       1691:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1692:     pDoc = pWin.document;
1.676     golterma 1693:     pDoc.write("<tr>");
                   1694:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1695:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1696:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1697: }
                   1698: 
                   1699:   function newMsg(newmsg,shwsel) {
1.76      ng       1700:     pDoc = pWin.document;
1.676     golterma 1701:     pDoc.write("<tr>");
                   1702:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.736     damieng  1703:     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1704:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1705: }
                   1706: 
                   1707:   function msgTail() {
1.76      ng       1708:     pDoc = pWin.document;
1.676     golterma 1709:     //pDoc.write("<\\/table>");
1.465     albertel 1710:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.736     damieng  1711:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1712:     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1713:     pDoc.write("<\\/form>");
1.351     albertel 1714:     pDoc.write('$end_page_msg_central');
1.128     ng       1715:     pDoc.close();
1.44      ng       1716: }
                   1717: 
                   1718: //====================== Script for keyword highlight options ==============
                   1719:   function kwhighlight() {
                   1720:     var kwclr    = document.SCORE.kwclr.value;
                   1721:     var kwsize   = document.SCORE.kwsize.value;
                   1722:     var kwstyle  = document.SCORE.kwstyle.value;
                   1723:     var redsel = "";
                   1724:     var grnsel = "";
                   1725:     var blusel = "";
1.736     damieng  1726:     var txtcol1 = "$js_lt{'col1'}";
                   1727:     var txtcol2 = "$js_lt{'col2'}";
                   1728:     var txtcol3 = "$js_lt{'col3'}";
                   1729:     var txtsiz1 = "$js_lt{'siz1'}";
                   1730:     var txtsiz2 = "$js_lt{'siz2'}";
                   1731:     var txtsiz3 = "$js_lt{'siz3'}";
                   1732:     var txtsty1 = "$js_lt{'sty1'}";
                   1733:     var txtsty2 = "$js_lt{'sty2'}";
                   1734:     var txtsty3 = "$js_lt{'sty3'}";
1.718     bisitz   1735:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1736:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1737:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1738:     var sznsel = "";
                   1739:     var sz1sel = "";
                   1740:     var sz2sel = "";
1.718     bisitz   1741:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1742:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1743:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1744:     var synsel = "";
                   1745:     var syisel = "";
                   1746:     var sybsel = "";
1.718     bisitz   1747:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1748:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1749:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1750:     highlightCentral();
1.718     bisitz   1751:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1752:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1753:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1754:     highlightend();
                   1755:     return;
                   1756:   }
                   1757: 
                   1758:   function highlightCentral() {
1.76      ng       1759: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1760:     var xpos = (screen.width-400)/2;
                   1761:     xpos = (xpos < 0) ? '0' : xpos;
                   1762:     var ypos = (screen.height-330)/2-30;
                   1763:     ypos = (ypos < 0) ? '0' : ypos;
                   1764: 
1.206     albertel 1765:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1766:     hwdWin.focus();
                   1767:     var hDoc = hwdWin.document;
1.219     www      1768:     hDoc.$docopen;
1.351     albertel 1769:     hDoc.write('$start_page_highlight_central');
1.76      ng       1770:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.736     damieng  1771:     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1772: 
1.718     bisitz   1773:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1.736     damieng  1774:     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1775:   }
                   1776: 
                   1777:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1778:     var hDoc = hwdWin.document;
1.718     bisitz   1779:     hDoc.write("<tr>");
1.76      ng       1780:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1781:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1782:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1783:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1784:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1785:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1786:     hDoc.write("<\\/tr>");
1.44      ng       1787:   }
                   1788: 
                   1789:   function highlightend() { 
1.76      ng       1790:     var hDoc = hwdWin.document;
1.718     bisitz   1791:     hDoc.write("<\\/table><br \\/>");
1.736     damieng  1792:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1793:     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1794:     hDoc.write("<\\/form>");
1.351     albertel 1795:     hDoc.write('$end_page_highlight_central');
1.128     ng       1796:     hDoc.close();
1.44      ng       1797:   }
                   1798: 
                   1799: SUBJAVASCRIPT
                   1800: }
                   1801: 
1.349     albertel 1802: sub get_increment {
1.348     bowersj2 1803:     my $increment = $env{'form.increment'};
                   1804:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1805:         $increment != .1) {
                   1806:         $increment = 1;
                   1807:     }
                   1808:     return $increment;
                   1809: }
                   1810: 
1.585     bisitz   1811: sub gradeBox_start {
                   1812:     return (
                   1813:         &Apache::loncommon::start_data_table()
                   1814:        .&Apache::loncommon::start_data_table_header_row()
                   1815:        .'<th>'.&mt('Part').'</th>'
                   1816:        .'<th>'.&mt('Points').'</th>'
                   1817:        .'<th>&nbsp;</th>'
                   1818:        .'<th>'.&mt('Assign Grade').'</th>'
                   1819:        .'<th>'.&mt('Weight').'</th>'
                   1820:        .'<th>'.&mt('Grade Status').'</th>'
                   1821:        .&Apache::loncommon::end_data_table_header_row()
                   1822:     );
                   1823: }
                   1824: 
                   1825: sub gradeBox_end {
                   1826:     return (
                   1827:         &Apache::loncommon::end_data_table()
                   1828:     );
                   1829: }
1.71      ng       1830: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1831: sub gradeBox {
1.322     albertel 1832:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1833:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1834: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1835:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1836:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1837:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1838:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1839:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1840: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1841:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1842:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1843:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1844: 				       [$partid]);
                   1845:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1846:     if ($last_resets{$partid}) {
                   1847:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1848:     }
1.695     bisitz   1849:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1850:     my $ctr = 0;
1.348     bowersj2 1851:     my $thisweight = 0;
1.349     albertel 1852:     my $increment = &get_increment();
1.485     albertel 1853: 
                   1854:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1855:     while ($thisweight<=$wgt) {
1.532     bisitz   1856: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1857:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1858: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1859: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1860: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1861:         $thisweight += $increment;
1.71      ng       1862: 	$ctr++;
                   1863:     }
1.485     albertel 1864:     $radio.='</tr></table>';
                   1865: 
                   1866:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1867: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1868: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1869: 	$wgt.')" /></td>'."\n";
1.485     albertel 1870:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1871: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1872: 	' </td>'."\n";
                   1873:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1874: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1875:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1876: 	$line.='<option></option>'.
                   1877: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1878:     } else {
1.485     albertel 1879: 	$line.='<option selected="selected"></option>'.
                   1880: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1881:     }
1.485     albertel 1882:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1883: 
                   1884: 
                   1885:     $result .= 
1.695     bisitz   1886: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1887:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1888:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1889:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1890: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1891: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1892: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1893:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1894:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1895:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1896:         $aggtries.'" />'."\n";
1.582     raeburn  1897:     my $res_error;
                   1898:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1899:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1900:     if ($res_error) {
                   1901:         return &navmap_errormsg();
                   1902:     }
1.318     banghart 1903:     return $result;
                   1904: }
1.322     albertel 1905: 
                   1906: sub handback_box {
1.623     www      1907:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1908:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1909:     my (@respids);
1.652     raeburn  1910:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1911:     foreach my $part_response_id (@part_response_id) {
                   1912:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1913:         if ($part eq $partid) {
1.375     albertel 1914:             push(@respids,$resp);
1.323     banghart 1915:         }
                   1916:     }
1.318     banghart 1917:     my $result;
1.323     banghart 1918:     foreach my $respid (@respids) {
1.322     albertel 1919: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1920: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1921: 	next if (!@$files);
1.654     raeburn  1922: 	my $file_counter = 0;
1.313     banghart 1923: 	foreach my $file (@$files) {
1.368     banghart 1924: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1925:                 $file_counter++;
1.368     banghart 1926:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1927:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1928:     	        $file_disp = "$name.$ext";
                   1929:     	        $file = $file_path.$file_disp;
                   1930:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1931:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1932:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1933:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1934: 	    }
1.322     albertel 1935: 	}
1.654     raeburn  1936:         if ($file_counter) {
                   1937:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1938:                        '<span class="LC_info">'.
                   1939:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1940:         }
1.313     banghart 1941:     }
1.318     banghart 1942:     return $result;    
1.71      ng       1943: }
1.44      ng       1944: 
1.58      albertel 1945: sub show_problem {
1.382     albertel 1946:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1947:     my $rendered;
1.382     albertel 1948:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1949:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1950:     if ($mode eq 'both' or $mode eq 'text') {
                   1951: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1952: 						       $env{'request.course.id'},
                   1953: 						       undef,\%form);
1.144     albertel 1954:     }
1.58      albertel 1955:     if ($removeform) {
                   1956: 	$rendered=~s|<form(.*?)>||g;
                   1957: 	$rendered=~s|</form>||g;
1.374     albertel 1958: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1959:     }
1.144     albertel 1960:     my $companswer;
                   1961:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1962: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1963: 	$companswer=
                   1964: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1965: 						    $env{'request.course.id'},
                   1966: 						    %form);
1.144     albertel 1967:     }
1.58      albertel 1968:     if ($removeform) {
                   1969: 	$companswer=~s|<form(.*?)>||g;
                   1970: 	$companswer=~s|</form>||g;
1.144     albertel 1971: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1972:     }
1.671     raeburn  1973:     my $renderheading = &mt('View of the problem');
                   1974:     my $answerheading = &mt('Correct answer');
                   1975:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1976:         my $stu_fullname = $env{'form.fullname'};
                   1977:         if ($stu_fullname eq '') {
                   1978:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1979:         }
                   1980:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1981:         if ($forwhom ne '') {
                   1982:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1983:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1984:         }
                   1985:     }
1.468     albertel 1986:     $rendered=
1.588     bisitz   1987:         '<div class="LC_Box">'
1.671     raeburn  1988:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1989:        .$rendered
                   1990:        .'</div>';
1.468     albertel 1991:     $companswer=
1.588     bisitz   1992:         '<div class="LC_Box">'
1.671     raeburn  1993:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1994:        .$companswer
                   1995:        .'</div>';
1.468     albertel 1996:     my $result;
1.144     albertel 1997:     if ($mode eq 'both') {
1.588     bisitz   1998:         $result=$rendered.$companswer;
1.144     albertel 1999:     } elsif ($mode eq 'text') {
1.588     bisitz   2000:         $result=$rendered;
1.144     albertel 2001:     } elsif ($mode eq 'answer') {
1.588     bisitz   2002:         $result=$companswer;
1.144     albertel 2003:     }
1.71      ng       2004:     return $result;
1.58      albertel 2005: }
1.397     albertel 2006: 
1.396     banghart 2007: sub files_exist {
                   2008:     my ($r, $symb) = @_;
                   2009:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
                   2010:     foreach my $student (@students) {
                   2011:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 2012:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2013: 					      $udom,$uname);
1.396     banghart 2014:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 2015:         foreach my $submission (@$string) {
                   2016:             my ($partid,$respid) =
                   2017: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2018:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2019: 					   \%record);
                   2020:             return 1 if (@$files);
1.396     banghart 2021:         }
                   2022:     }
1.397     albertel 2023:     return 0;
1.396     banghart 2024: }
1.397     albertel 2025: 
1.394     banghart 2026: sub download_all_link {
                   2027:     my ($r,$symb) = @_;
1.621     www      2028:     unless (&files_exist($r, $symb)) {
                   2029:        $r->print(&mt('There are currently no submitted documents.'));
                   2030:        return;
                   2031:     }
1.395     albertel 2032:     my $all_students = 
                   2033: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2034: 
                   2035:     my $parts =
                   2036: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2037: 
1.394     banghart 2038:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2039:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2040:                              'cgi.'.$identifier.'.symb' => $symb,
                   2041:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2042:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2043: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      2044:     return;
                   2045: }
                   2046: 
                   2047: sub submit_download_link {
                   2048:     my ($request,$symb) = @_;
                   2049:     if (!$symb) { return ''; }
                   2050: #FIXME: Figure out which type of problem this is and provide appropriate download
1.750     raeburn  2051:     my $res_error;
                   2052:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                   2053:     if (ref($res_error)) {
                   2054:         if ($$res_error) {
                   2055:             $request->print(&mt('An error occurred retrieving response types'));
                   2056:             return;
                   2057:         }
                   2058:     }
                   2059:     my ($numupload,$numessay) = (0,0);
                   2060:     if (ref($responseType) eq 'HASH') {
                   2061:         foreach my $part (sort(keys(%$responseType))) {
                   2062:             foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
                   2063:                 my $responsetype = $responseType->{$part}->{$id};
                   2064:                 if ($responsetype eq 'essay') {
                   2065:                     my $uploadedfiletypes =
                   2066:                         &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
                   2067:                     if ($uploadedfiletypes) {
                   2068:                         $numupload++;
                   2069:                     } else {
                   2070:                         $numessay++;
                   2071:                     }
                   2072:                 }
                   2073:             }
                   2074:         }
                   2075:     }
                   2076:     if (($numupload) || ($numessay)) {
                   2077:         my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                   2078:         my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   2079:         my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
                   2080:         (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
                   2081:         if (ref($fullname) eq 'HASH') {
                   2082:             my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
                   2083:             if (@students) {
                   2084:                 @{$env{'form.stuinfo'}} = @students;
                   2085:                 if ($numupload) {
                   2086:                     &download_all_link($request,$symb);
                   2087:                 }
                   2088: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
                   2089: # Needs to omit user's identity if resource instance is for an anonymous survey.
                   2090:             } else {
                   2091:                 $request->print(&mt('No students match the criteria you selected'));
                   2092:             }
                   2093:         } else {
                   2094:             $request->print(&mt('Could not retrieve student information'));
                   2095:         }
                   2096:     } else {
                   2097:         $request->print(&mt('No essayresponse items found'));
                   2098:     }
                   2099:     return;
1.394     banghart 2100: }
1.395     albertel 2101: 
1.432     banghart 2102: sub build_section_inputs {
                   2103:     my $section_inputs;
                   2104:     if ($env{'form.section'} eq '') {
                   2105:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2106:     } else {
                   2107:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2108:         foreach my $section (@sections) {
1.432     banghart 2109:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2110:         }
                   2111:     }
                   2112:     return $section_inputs;
                   2113: }
                   2114: 
1.44      ng       2115: # --------------------------- show submissions of a student, option to grade 
                   2116: sub submission {
1.608     www      2117:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 2118:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2119:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2120:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2121:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      2122: 
1.605     www      2123:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 2124:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.746     raeburn  2125:     my $is_tool = ($symb =~ /ext\.tool$/);
1.753     raeburn  2126:     my ($essayurl,%coursedesc_by_cid);
1.104     albertel 2127: 
                   2128:     if (!&canview($usec)) {
1.712     bisitz   2129:         $request->print(
                   2130:             '<span class="LC_warning">'.
1.713     bisitz   2131:             &mt('Unable to view requested student.').
1.712     bisitz   2132:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2133:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2134:             '</span>');
1.104     albertel 2135: 	return;
                   2136:     }
                   2137: 
1.257     albertel 2138:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1.745     raeburn  2139:     unless ($is_tool) { 
                   2140:         if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2141:         if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2142:     }
1.257     albertel 2143:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2144:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2145: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2146: 	'/check.gif" height="16" border="0" />';
1.41      ng       2147: 
                   2148:     # header info
                   2149:     if ($counter == 0) {
                   2150: 	&sub_page_js($request);
1.621     www      2151: 	&sub_page_kw_js($request);
1.118     ng       2152: 
1.44      ng       2153: 	# option to display problem, only once else it cause problems 
                   2154:         # with the form later since the problem has a form.
1.257     albertel 2155: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2156: 	    my $mode;
1.257     albertel 2157: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2158: 		$mode='both';
1.257     albertel 2159: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2160: 		$mode='text';
1.257     albertel 2161: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2162: 		$mode='answer';
                   2163: 	    }
1.329     albertel 2164: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2165: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2166: 	}
1.441     www      2167: 
1.704     raeburn  2168: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2169:         # if this subroutine has been called once.
1.41      ng       2170: 	my %keyhash = ();
1.624     www      2171: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2172:         if (1) {
1.41      ng       2173: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2174: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2175: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2176: 
1.257     albertel 2177: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2178: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2179: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2180: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2181: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2182: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2183: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2184: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2185: 	}
1.257     albertel 2186: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2187: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2188: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2189: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2190: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2191: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2192: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2193: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2194: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2195: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2196: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2197: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2198: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2199: 			&build_section_inputs().
1.326     albertel 2200: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2201: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2202: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2203: #	if ($env{'form.handgrade'} eq 'yes') {
                   2204:         if (1) {
1.257     albertel 2205: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2206: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2207: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2208: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2209: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2210: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2211: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2212: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2213: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2214: 	    }
1.123     ng       2215: 	}
1.41      ng       2216: 	
                   2217: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2218: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2219: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2220: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2221: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2222: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2223: 		'" />'."\n".
                   2224: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2225: 	    $cts++;
                   2226: 	}
                   2227: 	$request->print($prnmsg);
1.32      ng       2228: 
1.624     www      2229: #	if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2230:         unless ($is_tool) {
1.652     raeburn  2231: 
                   2232:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2233:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2234:                           keyw => 'Keyword Options',
1.655     raeburn  2235:                           list => 'List',
1.652     raeburn  2236:                           past => 'Paste Selection to List',
1.661     www      2237:                           high => 'Highlight Attribute',
1.652     raeburn  2238:                      );    
1.88      www      2239: #
                   2240: # Print out the keyword options line
                   2241: #
1.718     bisitz   2242: 	    $request->print(
                   2243:                 '<div class="LC_columnSection">'
                   2244:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2245:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2246:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2247:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2248:  class="page">'.$lt{'past'}.'</a>',
                   2249:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2250:                     {legend => $lt{'keyw'}})
                   2251:                .'</fieldset></div>'
                   2252:             );
                   2253: 
1.88      www      2254: #
                   2255: # Load the other essays for similarity check
                   2256: #
1.753     raeburn  2257:             (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
                   2258:             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2259:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2260:                 my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2261:                 if ($cdom ne '' && $cnum ne '') {
                   2262:                     my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
                   2263:                     if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
                   2264:                         my $apath = $1.'_'.$id;
                   2265:                         $apath=~s/\W/\_/gs;
                   2266:                         &init_old_essays($symb,$apath,$cdom,$cnum);
                   2267:                     }
                   2268:                 }
                   2269:             } else {
                   2270: 	        my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
                   2271: 	        $apath=&escape($apath);
                   2272: 	        $apath=~s/\W/\_/gs;
                   2273:                 &init_old_essays($symb,$apath,$adom,$aname);
                   2274:             }
1.41      ng       2275:         }
                   2276:     }
1.44      ng       2277: 
1.441     www      2278: # This is where output for one specific student would start
1.592     bisitz   2279:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2280:     $request->print(
                   2281:         "\n\n"
                   2282:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2283:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2284:        ."\n"
                   2285:     );
1.441     www      2286: 
1.592     bisitz   2287:     # Show additional functions if allowed
                   2288:     if ($perm{'vgr'}) {
                   2289:         $request->print(
                   2290:             &Apache::loncommon::track_student_link(
1.708     bisitz   2291:                 'View recent activity',
1.592     bisitz   2292:                 $uname,$udom,'check')
                   2293:            .' '
                   2294:         );
                   2295:     }
                   2296:     if ($perm{'opa'}) {
                   2297:         $request->print(
                   2298:             &Apache::loncommon::pprmlink(
                   2299:                 &mt('Set/Change parameters'),
                   2300:                 $uname,$udom,$symb,'check'));
                   2301:     }
                   2302: 
                   2303:     # Show Problem
1.257     albertel 2304:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2305: 	my $mode;
1.257     albertel 2306: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2307: 	    $mode='both';
1.257     albertel 2308: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2309: 	    $mode='text';
1.257     albertel 2310: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2311: 	    $mode='answer';
                   2312: 	}
1.329     albertel 2313: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2314: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2315:     }
1.144     albertel 2316: 
1.257     albertel 2317:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2318:     my $res_error;
                   2319:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2320:     if ($res_error) {
                   2321:         $request->print(&navmap_errormsg());
                   2322:         return;
                   2323:     }
1.41      ng       2324: 
1.44      ng       2325:     # Display student info
1.41      ng       2326:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2327: 
1.745     raeburn  2328:     my $boxtitle = &mt('Submissions');
                   2329:     if ($is_tool) {
                   2330:         $boxtitle = &mt('Transactions')
                   2331:     }
1.590     bisitz   2332:     my $result='<div class="LC_Box">'
1.745     raeburn  2333:               .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
1.45      ng       2334:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2335:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2336: #    if ($env{'form.handgrade'} eq 'no') {
1.745     raeburn  2337:     unless ($is_tool) {
1.588     bisitz   2338:         $result.='<p class="LC_info">'
                   2339:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2340:                 ."</p>\n";
1.469     albertel 2341:     }
                   2342: 
1.118     ng       2343:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2344:     my $fullname;
                   2345:     my $col_fullnames = [];
1.624     www      2346: #    if ($env{'form.handgrade'} eq 'yes') {
1.745     raeburn  2347:     unless ($is_tool) {
1.464     albertel 2348: 	(my $sub_result,$fullname,$col_fullnames)=
                   2349: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2350: 				 $counter);
                   2351: 	$result.=$sub_result;
1.41      ng       2352:     }
1.44      ng       2353:     $request->print($result."\n");
1.702     kruse    2354:     
1.44      ng       2355:     # print student answer/submission
1.588     bisitz   2356:     # Options are (1) Handgraded submission only
1.44      ng       2357:     #             (2) Last submission, includes submission that is not handgraded 
                   2358:     #                  (for multi-response type part)
                   2359:     #             (3) Last submission plus the parts info
                   2360:     #             (4) The whole record for this student
1.702     kruse    2361:     
1.745     raeburn  2362:     my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
1.468     albertel 2363: 	
1.702     kruse    2364:     my $lastsubonly;
1.468     albertel 2365: 
1.702     kruse    2366:     if ($$timestamp eq '') {
                   2367:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.745     raeburn  2368:     } elsif ($is_tool) {
                   2369:         $lastsubonly =
                   2370:             '<div class="LC_grade_submissions_body">'
                   2371:            .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
1.702     kruse    2372:     } else {
                   2373:         $lastsubonly =
                   2374:             '<div class="LC_grade_submissions_body">'
                   2375:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2376: 
                   2377: 	my %seenparts;
                   2378: 	my @part_response_id = &flatten_responseType($responseType);
                   2379: 	foreach my $part (@part_response_id) {
                   2380: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2381: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2382: 
1.702     kruse    2383: 	    my ($partid,$respid) = @{ $part };
                   2384: 	    my $display_part=&get_display_part($partid,$symb);
                   2385: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2386: 		if (exists($seenparts{$partid})) { next; }
                   2387: 		$seenparts{$partid}=1;
                   2388:                 $request->print(
                   2389:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2390:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2391:                                '<a href="javascript:viewSubmitter(\''.
                   2392:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2393:                                '\');" target="_self">'.
                   2394:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2395:                     '<br />');
                   2396: 		next;
                   2397: 		}
                   2398: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2399: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2400:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2401:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2402:                     ' <span class="LC_internal_info">'.
                   2403:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2404:                     '</span>&nbsp; &nbsp;'.
                   2405: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2406: 		next;
                   2407: 	    }
                   2408: 	    foreach my $submission (@$string) {
                   2409: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2410: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2411: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2412: 		# Similarity check
                   2413:                 my $similar='';
                   2414:                 my ($type,$trial,$rndseed);
                   2415:                 if ($hide eq 'rand') {
                   2416:                     $type = 'randomizetry';
                   2417:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2418:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2419:                 }
                   2420: 	        if ($env{'form.checkPlag'}) {
                   2421:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2422: 		        &most_similar($uname,$udom,$symb,$subval);
                   2423: 		    if ($osim) {
                   2424: 			$osim=int($osim*100.0);
                   2425:                         if ($hide eq 'anon') {
                   2426:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2427:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2428:                         } else {
1.753     raeburn  2429: 			    $similar='<hr />';
                   2430:                             if ($essayurl eq 'lib/templates/simpleproblem.problem') {
                   2431:                                 $similar .= '<h3><span class="LC_warning">'.
                   2432:                                             &mt('Essay is [_1]% similar to an essay by [_2]',
                   2433:                                                 $osim,
                   2434:                                                 &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2435:                                             '</span></h3>';
                   2436:                             } else {
                   2437:                                 my %old_course_desc;
                   2438:                                 if ($ocrsid ne '') {
                   2439:                                     if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
                   2440:                                         %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
                   2441:                                     } else {
                   2442:                                         my $args;
                   2443:                                         if ($ocrsid ne $env{'request.course.id'}) {
                   2444:                                             $args = {'one_time' => 1};
                   2445:                                         }
                   2446:                                         %old_course_desc =
                   2447:                                             &Apache::lonnet::coursedescription($ocrsid,$args);
                   2448:                                         $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
                   2449:                                     }
                   2450:                                     $similar .=
                   2451:                                         '<h3><span class="LC_warning">'.
                   2452:                                         &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2453:                                             $osim,
                   2454:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2455:                                             $old_course_desc{'description'},
                   2456:                                             $old_course_desc{'num'},
                   2457:                                             $old_course_desc{'domain'}).
                   2458:                                         '</span></h3>';
                   2459:                                 } else {
                   2460:                                     $similar .=
                   2461:                                         '<h3><span class="LC_warning">'.
                   2462:                                         &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
                   2463:                                             $osim,
                   2464:                                             &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
                   2465:                                         '</span></h3>';
                   2466:                                 }
                   2467:                             }
                   2468:                             $similar .= '<blockquote><i>'.
                   2469:                                         &keywords_highlight($oessay).
                   2470:                                         '</i></blockquote><hr />';
1.702     kruse    2471:                         }
                   2472: 	            }
                   2473: 		}
                   2474: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2475:                                      undef,$type,$trial,$rndseed);
                   2476:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2477: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2478: 		    my $display_part=&get_display_part($partid,$symb);
                   2479:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2480:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2481:                         ' <span class="LC_internal_info">'.
                   2482:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2483:                         '</span>&nbsp; &nbsp;';
                   2484: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2485:                         
                   2486: 		    if (@$files) {
                   2487:                         if ($hide eq 'anon') {
                   2488:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2489:                         } else {
                   2490:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2491:                                         .'<br /><span class="LC_warning">';
                   2492:                             if(@$files == 1) {
                   2493:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2494:                             } else {
1.702     kruse    2495:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2496:                             }
                   2497:                             $lastsubonly .= '</span>';                         
                   2498:                             foreach my $file (@$files) {
                   2499:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2500:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2501:                             }
                   2502:                         }
1.702     kruse    2503: 			$lastsubonly.='<br />';
                   2504:                     }
                   2505:                     if ($hide eq 'anon') {
                   2506:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2507:                     } else {
1.724     raeburn  2508:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2509:                         if ($draft) {
                   2510:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2511:                         }
                   2512:                         $subval =
1.702     kruse    2513: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2514: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2515:                         if ($responsetype eq 'essay') {
                   2516:                             $subval =~ s{\n}{<br />}g;
                   2517:                         }
                   2518:                         $lastsubonly.=$subval."\n";
1.702     kruse    2519:                     }
                   2520: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2521: 		    $lastsubonly.='</div>';
1.41      ng       2522: 		}
1.702     kruse    2523:             }
1.151     albertel 2524: 	}
1.702     kruse    2525: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2526:     }
                   2527:     $request->print($lastsubonly);
                   2528:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2529:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2530: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2531:   
1.702     kruse    2532:     } 
                   2533:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2534:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2535:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2536: 								 $env{'request.course.id'},
1.44      ng       2537: 								 $last,'.submission',
1.726     raeburn  2538: 								 'Apache::grades::keywords_highlight',
                   2539:                                                                  $usec,$identifier));
1.41      ng       2540:     }
1.121     ng       2541:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2542: 	.$udom.'" />'."\n");
1.44      ng       2543:     # return if view submission with no grading option
1.618     www      2544:     if (!&canmodify($usec)) {
1.633     www      2545: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2546: 	return;
1.180     albertel 2547:     } else {
1.468     albertel 2548: 	$request->print('</div>'."\n");
1.41      ng       2549:     }
1.33      ng       2550: 
1.121     ng       2551:     # essay grading message center
1.624     www      2552: #    if ($env{'form.handgrade'} eq 'yes') {
                   2553:     if (1) {
1.468     albertel 2554: 	my $result='<div class="LC_grade_message_center">';
                   2555:     
                   2556: 	$result.='<div class="LC_grade_message_center_header">'.
                   2557: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2558: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2559: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2560: 	if (scalar(@$col_fullnames) > 0) {
                   2561: 	    my $lastone = pop(@$col_fullnames);
                   2562: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2563: 	}
                   2564: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2565: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2566: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2567: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2568: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2569: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2570: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2571: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2572: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2573: 	    '<br />&nbsp;('.
1.468     albertel 2574: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2575: 	$result.='</div></div>';
1.121     ng       2576: 	$request->print($result);
1.118     ng       2577:     }
1.41      ng       2578: 
                   2579:     my %seen = ();
                   2580:     my @partlist;
1.129     ng       2581:     my @gradePartRespid;
1.745     raeburn  2582:     my @part_response_id;
                   2583:     if ($is_tool) {
                   2584:         @part_response_id = ([0,'']);
                   2585:     } else {
                   2586:         @part_response_id = &flatten_responseType($responseType);
                   2587:     }
1.585     bisitz   2588:     $request->print(
1.588     bisitz   2589:         '<div class="LC_Box">'
                   2590:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2591:     );
1.592     bisitz   2592:     $request->print(&gradeBox_start());
1.375     albertel 2593:     foreach my $part_response_id (@part_response_id) {
                   2594:     	my ($partid,$respid) = @{ $part_response_id };
                   2595: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2596: 	next if ($seen{$partid} > 0);
1.41      ng       2597: 	$seen{$partid}++;
1.393     albertel 2598: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2599: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2600: 	push(@partlist,$partid);
                   2601: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2602: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2603:     }
1.585     bisitz   2604:     $request->print(&gradeBox_end()); # </div>
                   2605:     $request->print('</div>');
1.468     albertel 2606: 
                   2607:     $request->print('<div class="LC_grade_info_links">');
                   2608:     $request->print('</div>');
                   2609: 
1.45      ng       2610:     $result='<input type="hidden" name="partlist'.$counter.
                   2611: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2612:     $result.='<input type="hidden" name="gradePartRespid'.
                   2613: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2614:     my $ctr = 0;
                   2615:     while ($ctr < scalar(@partlist)) {
                   2616: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2617: 	    $partlist[$ctr].'" />'."\n";
                   2618: 	$ctr++;
                   2619:     }
1.468     albertel 2620:     $request->print($result.''."\n");
1.41      ng       2621: 
1.441     www      2622: # Done with printing info for one student
                   2623: 
1.468     albertel 2624:     $request->print('</div>');#LC_grade_show_user
1.441     www      2625: 
                   2626: 
1.41      ng       2627:     # print end of form
                   2628:     if ($counter == $total) {
1.592     bisitz   2629:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2630: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2631: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2632: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2633: 	my $ntstu ='<select name="NTSTU">'.
                   2634: 	    '<option>1</option><option>2</option>'.
                   2635: 	    '<option>3</option><option>5</option>'.
                   2636: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2637: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2638: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2639:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2640: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2641: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2642: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2643: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2644:         $endform.='<span class="LC_warning">'.
                   2645:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2646:                   '</span>'."\n" ;
1.349     albertel 2647:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2648:             "' name='increment' />";
1.485     albertel 2649: 	$endform.='</td></tr></table></form>';
1.41      ng       2650: 	$request->print($endform);
                   2651:     }
                   2652:     return '';
1.38      ng       2653: }
                   2654: 
1.464     albertel 2655: sub check_collaborators {
                   2656:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2657:     my ($result,@col_fullnames);
                   2658:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2659:     foreach my $part (keys(%$handgrade)) {
                   2660: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2661: 					'.maxcollaborators',
                   2662: 					$symb,$udom,$uname);
                   2663: 	next if ($ncol <= 0);
                   2664: 	$part =~ s/\_/\./g;
                   2665: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2666: 	my (@good_collaborators, @bad_collaborators);
                   2667: 	foreach my $possible_collaborator
1.630     www      2668: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2669: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2670: 	    next if ($possible_collaborator eq '');
1.631     www      2671: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2672: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2673: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2674: 	    # Doing this grep allows 'fuzzy' specification
                   2675: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2676: 			       keys(%$classlist));
                   2677: 	    if (! scalar(@matches)) {
                   2678: 		push(@bad_collaborators, $possible_collaborator);
                   2679: 	    } else {
                   2680: 		push(@good_collaborators, @matches);
                   2681: 	    }
                   2682: 	}
                   2683: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2684: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2685: 	    foreach my $name (@good_collaborators) {
                   2686: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2687: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2688: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2689: 	    }
1.630     www      2690: 	    $result.='</ol><br />'."\n";
1.466     albertel 2691: 	    my ($part)=split(/\./,$part);
1.464     albertel 2692: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2693: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2694: 		"\n";
                   2695: 	}
                   2696: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2697: 	    $result.='<div class="LC_warning">';
1.464     albertel 2698: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2699: 	    $result .= '</div>';
                   2700: 	}         
                   2701: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2702: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2703: 	    $result .= &mt('This student has submitted too many '.
                   2704: 		'collaborators.  Maximum is [_1].',$ncol);
                   2705: 	    $result .= '</div>';
                   2706: 	}
                   2707:     }
                   2708:     return ($result,$fullname,\@col_fullnames);
                   2709: }
                   2710: 
1.44      ng       2711: #--- Retrieve the last submission for all the parts
1.38      ng       2712: sub get_last_submission {
1.745     raeburn  2713:     my ($returnhash,$is_tool)=@_;
1.596     raeburn  2714:     my (@string,$timestamp,%lasthidden);
1.119     ng       2715:     if ($$returnhash{'version'}) {
1.46      ng       2716: 	my %lasthash=();
                   2717: 	my ($version);
1.119     ng       2718: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2719: 	    foreach my $key (sort(split(/\:/,
                   2720: 					$$returnhash{$version.':keys'}))) {
                   2721: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2722: 		$timestamp = 
1.545     raeburn  2723: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2724: 	    }
                   2725: 	}
1.640     raeburn  2726:         my (%typeparts,%randombytry);
1.596     raeburn  2727:         my $showsurv = 
                   2728:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2729:         foreach my $key (sort(keys(%lasthash))) {
                   2730:             if ($key =~ /\.type$/) {
                   2731:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2732:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2733:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2734:                     my ($ign,@parts) = split(/\./,$key);
                   2735:                     pop(@parts);
1.641     raeburn  2736:                     my $id = join('.',@parts);
1.640     raeburn  2737:                     if ($lasthash{$key} eq 'randomizetry') {
                   2738:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2739:                     } else {
                   2740:                         unless ($showsurv) {
                   2741:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2742:                         }
1.596     raeburn  2743:                     }
                   2744:                     delete($lasthash{$key});
                   2745:                 }
                   2746:             }
                   2747:         }
                   2748:         my @hidden = keys(%typeparts);
1.640     raeburn  2749:         my @randomize = keys(%randombytry);
1.397     albertel 2750: 	foreach my $key (keys(%lasthash)) {
                   2751: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2752:             my $hide;
                   2753:             if (@hidden) {
                   2754:                 foreach my $id (@hidden) {
                   2755:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2756:                         $hide = 'anon';
1.596     raeburn  2757:                         last;
                   2758:                     }
                   2759:                 }
                   2760:             }
1.640     raeburn  2761:             unless ($hide) {
                   2762:                 if (@randomize) {
1.732     raeburn  2763:                     foreach my $id (@randomize) {
1.640     raeburn  2764:                         if ($key =~ /^\Q$id\E/) {
                   2765:                             $hide = 'rand';
                   2766:                             last;
                   2767:                         }
                   2768:                     }
                   2769:                 }
                   2770:             }
1.397     albertel 2771: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2772: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2773:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2774:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2775:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2776: 	}
                   2777:     }
1.397     albertel 2778:     if (!@string) {
1.745     raeburn  2779:         my $msg;
                   2780:         if ($is_tool) {
1.747     raeburn  2781:             $msg = &mt('No grade passed back.');
1.745     raeburn  2782:         } else {
                   2783:             $msg = &mt('Nothing submitted - no attempts.');
                   2784:         }
1.397     albertel 2785: 	$string[0] =
1.745     raeburn  2786: 	    '<span class="LC_warning">'.$msg.'</span>';
1.397     albertel 2787:     }
                   2788:     return (\@string,\$timestamp);
1.38      ng       2789: }
1.35      ng       2790: 
1.44      ng       2791: #--- High light keywords, with style choosen by user.
1.38      ng       2792: sub keywords_highlight {
1.44      ng       2793:     my $string    = shift;
1.257     albertel 2794:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2795:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2796:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2797:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2798:     foreach my $keyword (@keylist) {
                   2799: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2800:     }
                   2801:     return $string;
1.38      ng       2802: }
1.36      ng       2803: 
1.671     raeburn  2804: # For Tasks provide a mechanism to display previous version for one specific student
                   2805: 
                   2806: sub show_previous_task_version {
                   2807:     my ($request,$symb) = @_;
                   2808:     if ($symb eq '') {
1.717     bisitz   2809:         $request->print(
                   2810:             '<span class="LC_error">'.
                   2811:             &mt('Unable to handle ambiguous references.').
                   2812:             '</span>');
1.671     raeburn  2813:         return '';
                   2814:     }
                   2815:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2816:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2817:     if (!&canview($usec)) {
1.712     bisitz   2818:         $request->print(
                   2819:             '<span class="LC_warning">'.
1.713     bisitz   2820:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2821:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2822:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2823:             '</span>');
1.671     raeburn  2824:         return;
                   2825:     }
                   2826:     my $mode = 'both';
                   2827:     my $isTask = ($symb =~/\.task$/);
                   2828:     if ($isTask) {
                   2829:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2830:             if ($env{'form.fullname'} eq '') {
                   2831:                 $env{'form.fullname'} =
                   2832:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2833:             }
                   2834:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2835:             $request->print("\n\n".
                   2836:                             '<div class="LC_grade_show_user">'.
                   2837:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2838:                             '</h2>'."\n");
                   2839:             &Apache::lonxml::clear_problem_counter();
                   2840:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2841:                             {'previousversion' => $env{'form.previousversion'} }));
                   2842:             $request->print("\n</div>");
                   2843:         }
                   2844:     }
                   2845:     return;
                   2846: }
                   2847: 
                   2848: sub choose_task_version_form {
                   2849:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2850:     my $isTask = ($symb =~/\.task$/);
                   2851:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2852:     if ($isTask) {
                   2853:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2854:                                               $udom,$uname);
                   2855:         if (($record{'resource.0.version'} eq '') ||
                   2856:             ($record{'resource.0.version'} < 2)) {
                   2857:             return ($record{'resource.0.version'},
                   2858:                     $record{'resource.0.version'},$result,$js);
                   2859:         } else {
                   2860:             $current = $record{'resource.0.version'};
                   2861:         }
                   2862:         if ($env{'form.previousversion'}) {
                   2863:             $displayed = $env{'form.previousversion'};
                   2864:             $rowtitle = &mt('Choose another version:')
                   2865:         } else {
                   2866:             $displayed = $current;
                   2867:             $rowtitle = &mt('Show earlier version:');
                   2868:         }
                   2869:         $result = '<div class="LC_left_float">';
                   2870:         my $list;
                   2871:         my $numversions = 0;
                   2872:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2873:             if ($i == $current) {
                   2874:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2875:                     next;
                   2876:                 } else {
                   2877:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2878:                     $numversions ++;
                   2879:                 }
                   2880:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2881:                 unless ($i == $env{'form.previousversion'}) {
                   2882:                     $numversions ++;
                   2883:                 }
                   2884:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2885:             }
                   2886:         }
                   2887:         if ($numversions) {
                   2888:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2889:             $result .=
                   2890:                 '<form name="getprev" method="post" action=""'.
                   2891:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2892:                 &Apache::loncommon::start_data_table().
                   2893:                 &Apache::loncommon::start_data_table_row().
                   2894:                 '<th align="left">'.$rowtitle.'</th>'.
                   2895:                 '<td><select name="version">'.
                   2896:                 '<option>'.&mt('Select').'</option>'.
                   2897:                 $list.
                   2898:                 '</select></td>'.
                   2899:                 &Apache::loncommon::end_data_table_row();
                   2900:             unless ($nomenu) {
                   2901:                 $result .= &Apache::loncommon::start_data_table_row().
                   2902:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2903:                 '<td><span class="LC_nobreak">'.
                   2904:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2905:                 &mt('Yes').'</label>'.
                   2906:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2907:                 '</span></td>'.
                   2908:                 &Apache::loncommon::end_data_table_row();
                   2909:             }
                   2910:             $result .=
                   2911:                 &Apache::loncommon::start_data_table_row().
                   2912:                 '<th align="left">&nbsp;</th>'.
                   2913:                 '<td>'.
                   2914:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2915:                 '</td>'.
                   2916:                 &Apache::loncommon::end_data_table_row().
                   2917:                 &Apache::loncommon::end_data_table().
                   2918:                 '</form>';
                   2919:             $js = &previous_display_javascript($nomenu,$current);
                   2920:         } elsif ($displayed && $nomenu) {
                   2921:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2922:         } else {
                   2923:             $result .= &mt('No previous versions to show for this student');
                   2924:         }
                   2925:         $result .= '</div>';
                   2926:     }
                   2927:     return ($current,$displayed,$result,$js);
                   2928: }
                   2929: 
                   2930: sub previous_display_javascript {
                   2931:     my ($nomenu,$current) = @_;
                   2932:     my $js = <<"JSONE";
                   2933: <script type="text/javascript">
                   2934: // <![CDATA[
                   2935: function previousVersion(uname,udom,symb) {
                   2936:     var current = '$current';
                   2937:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2938:     var prevstr = new RegExp("^\\\\d+\$");
                   2939:     if (!prevstr.test(version)) {
                   2940:         return false;
                   2941:     }
                   2942:     var url = '';
                   2943:     if (version == current) {
                   2944:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2945:     } else {
                   2946:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2947:     }
                   2948: JSONE
                   2949:     if ($nomenu) {
                   2950:         $js .= <<"JSTWO";
                   2951:     document.location.href = url;
                   2952: JSTWO
                   2953:     } else {
                   2954:         $js .= <<"JSTHREE";
                   2955:     var newwin = 0;
                   2956:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2957:         if (document.getprev.prevwin[i].checked == true) {
                   2958:             newwin = document.getprev.prevwin[i].value;
                   2959:         }
                   2960:     }
                   2961:     if (newwin == 1) {
                   2962:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2963:         url = url+'&inhibitmenu=yes';
                   2964:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2965:             previousWin = window.open(url,'',options,1);
                   2966:         } else {
                   2967:             previousWin.location.href = url;
                   2968:         }
                   2969:         previousWin.focus();
                   2970:         return false;
                   2971:     } else {
                   2972:         document.location.href = url;
                   2973:         return false;
                   2974:     }
                   2975: JSTHREE
                   2976:     }
                   2977:     $js .= <<"ENDJS";
                   2978:     return false;
                   2979: }
                   2980: // ]]>
                   2981: </script>
                   2982: ENDJS
                   2983: 
                   2984: }
                   2985: 
1.44      ng       2986: #--- Called from submission routine
1.38      ng       2987: sub processHandGrade {
1.608     www      2988:     my ($request,$symb) = @_;
1.324     albertel 2989:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2990:     my $button = $env{'form.gradeOpt'};
                   2991:     my $ngrade = $env{'form.NCT'};
                   2992:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2993:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2994:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2995: 
1.44      ng       2996:     if ($button eq 'Save & Next') {
                   2997: 	my $ctr = 0;
                   2998: 	while ($ctr < $ngrade) {
1.257     albertel 2999: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  3000: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   3001:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       3002: 	    if ($errorflag eq 'no_score') {
                   3003: 		$ctr++;
                   3004: 		next;
                   3005: 	    }
1.104     albertel 3006: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   3007: 		$request->print(
                   3008:                     '<span class="LC_error">'
                   3009:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   3010:                    .'</span>');
1.104     albertel 3011: 		$ctr++;
                   3012: 		next;
                   3013: 	    }
1.726     raeburn  3014:             if ($numhidden) {
                   3015:                 $request->print(
                   3016:                     '<span class="LC_info">'
                   3017:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   3018:                    .'</span><br />');
                   3019:             }
1.257     albertel 3020: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       3021: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 3022: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   3023:             my ($feedurl,$showsymb) =
                   3024: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   3025: 	    my $messagetail;
1.62      albertel 3026: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      3027: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      3028: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  3029: 		$subject.=' ['.$restitle.']';
1.44      ng       3030: 		my (@msgnum) = split(/,/,$includemsg);
                   3031: 		foreach (@msgnum) {
1.257     albertel 3032: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       3033: 		}
1.80      ng       3034: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      3035: 		if ($env{'form.withgrades'.$ctr}) {
                   3036: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  3037: 		    $messagetail = " for <a href=\"".
1.605     www      3038: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  3039: 		}
                   3040: 		$msgstatus = 
                   3041:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   3042: 						     $message.$messagetail,
1.418     albertel 3043:                                                      undef,$feedurl,undef,
1.386     raeburn  3044:                                                      undef,undef,$showsymb,
                   3045:                                                      $restitle);
1.574     bisitz   3046: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  3047: 				$msgstatus.'<br />');
1.44      ng       3048: 	    }
1.257     albertel 3049: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 3050: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 3051: 		foreach my $collabstr (@collabstrs) {
                   3052: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 3053: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 3054: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 3055: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 3056: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 3057: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 3058: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 3059: 			    next;
1.418     albertel 3060: 			} elsif ($message ne '') {
                   3061: 			    my ($baseurl,$showsymb) = 
                   3062: 				&get_feedurl_and_symb($symb,$collaborator,
                   3063: 						      $udom);
                   3064: 			    if ($env{'form.withgrades'.$ctr}) {
                   3065: 				$messagetail = " for <a href=\"".
1.605     www      3066:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 3067: 			    }
1.418     albertel 3068: 			    $msgstatus = 
                   3069: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 3070: 			}
1.44      ng       3071: 		    }
                   3072: 		}
                   3073: 	    }
                   3074: 	    $ctr++;
                   3075: 	}
                   3076:     }
                   3077: 
1.624     www      3078: #    if ($env{'form.handgrade'} eq 'yes') {
                   3079:     if (1) {
1.119     ng       3080: 	# Keywords sorted in alphabatical order
1.257     albertel 3081: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       3082: 	my %keyhash = ();
1.257     albertel 3083: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   3084: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   3085: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   3086: 	$env{'form.keywords'} = join(' ',@keywords);
                   3087: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   3088: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   3089: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   3090: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   3091: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       3092: 
                   3093: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 3094: 	# New messages are saved in env for the next student.
1.119     ng       3095: 	# All messages are saved in nohist_handgrade.db
                   3096: 	my ($ctr,$idx) = (1,1);
1.257     albertel 3097: 	while ($ctr <= $env{'form.savemsgN'}) {
                   3098: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   3099: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       3100: 		$idx++;
                   3101: 	    }
                   3102: 	    $ctr++;
1.41      ng       3103: 	}
1.119     ng       3104: 	$ctr = 0;
                   3105: 	while ($ctr < $ngrade) {
1.257     albertel 3106: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   3107: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   3108: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       3109: 		$idx++;
                   3110: 	    }
                   3111: 	    $ctr++;
1.41      ng       3112: 	}
1.257     albertel 3113: 	$env{'form.savemsgN'} = --$idx;
                   3114: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       3115: 	my $putresult = &Apache::lonnet::put
1.301     albertel 3116: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       3117:     }
1.44      ng       3118:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 3119:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   3120:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       3121: 	my ($ctr,$total) = (0,0);
                   3122: 	while ($ctr < $ngrade) {
1.257     albertel 3123: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       3124: 	    $ctr++;
                   3125: 	}
1.257     albertel 3126: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3127: 	$ctr = 0;
                   3128: 	while ($ctr < $total) {
1.257     albertel 3129: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3130: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3131: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      3132: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       3133: 	    $ctr++;
                   3134: 	}
                   3135: 	return '';
                   3136:     }
1.36      ng       3137: 
1.44      ng       3138:     # Get the next/previous one or group of students
1.257     albertel 3139:     my $firststu = $env{'form.unamedom0'};
                   3140:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3141:     my $ctr = 2;
1.41      ng       3142:     while ($laststu eq '') {
1.257     albertel 3143: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3144: 	$ctr++;
                   3145: 	$laststu = $firststu if ($ctr > $ngrade);
                   3146:     }
1.44      ng       3147: 
1.41      ng       3148:     my (@parsedlist,@nextlist);
                   3149:     my ($nextflg) = 0;
1.524     raeburn  3150:     foreach my $item (sort 
1.294     albertel 3151: 	     {
                   3152: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3153: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3154: 		 }
                   3155: 		 return $a cmp $b;
                   3156: 	     } (keys(%$fullname))) {
1.605     www      3157: # FIXME: this is fishy, looks like the button label
1.41      ng       3158: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3159: 	    push(@parsedlist,$item);
1.41      ng       3160: 	}
1.524     raeburn  3161: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3162: 	if ($button eq 'Previous') {
1.524     raeburn  3163: 	    last if ($item eq $firststu);
                   3164: 	    push(@parsedlist,$item);
1.41      ng       3165: 	}
                   3166:     }
                   3167:     $ctr = 0;
1.605     www      3168: # FIXME: this is fishy, looks like the button label
1.41      ng       3169:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3170:     my $res_error;
                   3171:     my ($partlist) = &response_type($symb,\$res_error);
                   3172:     if ($res_error) {
                   3173:         $request->print(&navmap_errormsg());
                   3174:         return;
                   3175:     }
1.41      ng       3176:     foreach my $student (@parsedlist) {
1.257     albertel 3177: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3178: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3179: 	
                   3180: 	if ($submitonly eq 'queued') {
                   3181: 	    my %queue_status = 
                   3182: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3183: 							$udom,$uname);
                   3184: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3185: 	}
                   3186: 
1.156     albertel 3187: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3188: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3189: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3190: 	    my $submitted = 0;
1.248     albertel 3191: 	    my $ungraded = 0;
                   3192: 	    my $incorrect = 0;
1.524     raeburn  3193: 	    foreach my $item (keys(%status)) {
                   3194: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3195: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3196: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3197: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3198: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3199: 		    $submitted = 0;
                   3200: 		}
1.41      ng       3201: 	    }
1.156     albertel 3202: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3203: 				     $submitonly eq 'incorrect' ||
                   3204: 				     $submitonly eq 'graded'));
1.248     albertel 3205: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3206: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3207: 	}
1.524     raeburn  3208: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3209: 	last if ($ctr == $ntstu);
1.41      ng       3210: 	$ctr++;
                   3211:     }
1.36      ng       3212: 
1.41      ng       3213:     $ctr = 0;
                   3214:     my $total = scalar(@nextlist)-1;
1.39      ng       3215: 
1.524     raeburn  3216:     foreach (sort(@nextlist)) {
1.41      ng       3217: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3218: 	$env{'form.student'}  = $uname;
                   3219: 	$env{'form.userdom'}  = $udom;
                   3220: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      3221: 	&submission($request,$ctr,$total,$symb);
1.41      ng       3222: 	$ctr++;
                   3223:     }
                   3224:     if ($total < 0) {
1.653     raeburn  3225: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3226: 	$request->print($the_end);
                   3227:     }
                   3228:     return '';
1.38      ng       3229: }
1.36      ng       3230: 
1.44      ng       3231: #---- Save the score and award for each student, if changed
1.38      ng       3232: sub saveHandGrade {
1.324     albertel 3233:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3234:     my @version_parts;
1.104     albertel 3235:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3236: 					   $env{'request.course.id'});
1.104     albertel 3237:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3238:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3239:     my @parts_graded;
1.77      ng       3240:     my %newrecord  = ();
1.726     raeburn  3241:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3242:     my %aggregate = ();
                   3243:     my $aggregateflag = 0;
1.726     raeburn  3244:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3245:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3246:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3247:         $totchg += $numchgs;
                   3248:     }
1.301     albertel 3249:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3250:     foreach my $new_part (@parts) {
1.337     banghart 3251: 	#collaborator ($submi may vary for different parts
1.259     banghart 3252: 	if ($submitter && $new_part ne $part) { next; }
                   3253: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3254: 	if ($dropMenu eq 'excused') {
1.259     banghart 3255: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3256: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3257: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3258: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3259: 		}
1.364     banghart 3260: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3261: 	    }
1.125     ng       3262: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3263: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3264: 	    foreach my $key (keys(%record)) {
1.259     banghart 3265: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3266: 	    }
1.259     banghart 3267: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3268: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3269:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3270: 
                   3271:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3272: 					       [$new_part]);
                   3273:             my $aggtries =$totaltries;
1.269     raeburn  3274:             if ($last_resets{$new_part}) {
1.270     albertel 3275:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3276: 					   $new_part);
1.269     raeburn  3277:             }
1.270     albertel 3278: 
                   3279:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3280:             if ($aggtries > 0) {
1.327     albertel 3281:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3282:                 $aggregateflag = 1;
                   3283:             }
1.125     ng       3284: 	} elsif ($dropMenu eq '') {
1.259     banghart 3285: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3286: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3287: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3288: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3289: 		next;
                   3290: 	    }
1.259     banghart 3291: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3292: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3293: 	    my $partial= $pts/$wgt;
1.259     banghart 3294: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3295: 		#do not update score for part if not changed.
1.346     banghart 3296:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3297: 		next;
1.251     banghart 3298: 	    } else {
1.524     raeburn  3299: 	        push(@parts_graded,$new_part);
1.153     albertel 3300: 	    }
1.259     banghart 3301: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3302: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3303: 	    }
1.259     banghart 3304: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3305: 	    if ($partial == 0) {
1.153     albertel 3306: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3307: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3308: 		}
1.41      ng       3309: 	    } else {
1.153     albertel 3310: 		if ($record{$reckey} ne 'correct_by_override') {
                   3311: 		    $newrecord{$reckey} = 'correct_by_override';
                   3312: 		}
                   3313: 	    }	    
                   3314: 	    if ($submitter && 
1.259     banghart 3315: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3316: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3317: 	    }
1.259     banghart 3318: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3319: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3320: 	}
1.259     banghart 3321: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3322: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3323: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3324: 	        $dropMenu eq 'reset status')
                   3325: 	   {
1.524     raeburn  3326: 	    push(@version_parts,$new_part);
1.259     banghart 3327: 	}
1.41      ng       3328:     }
1.301     albertel 3329:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3330:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3331: 
1.344     albertel 3332:     if (%newrecord) {
                   3333:         if (@version_parts) {
1.364     banghart 3334:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3335:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3336: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3337: 	    foreach my $new_part (@version_parts) {
                   3338: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3339: 				$new_part,\%newrecord);
                   3340: 	    }
1.259     banghart 3341:         }
1.44      ng       3342: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3343: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3344: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3345: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3346:     }
1.269     raeburn  3347:     if ($aggregateflag) {
                   3348:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3349: 			      $cdom,$cnum);
1.269     raeburn  3350:     }
1.726     raeburn  3351:     return ('',$pts,$wgt,$totchg);
                   3352: }
                   3353: 
                   3354: sub makehidden {
1.728     raeburn  3355:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3356:     return unless (ref($record) eq 'HASH');
                   3357:     my %modified;
                   3358:     my $numchanged = 0;
                   3359:     if (exists($record->{$version.':keys'})) {
                   3360:         my $partsregexp = $parts;
                   3361:         $partsregexp =~ s/,/|/g;
                   3362:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3363:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3364:                  my $item = $1;
                   3365:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3366:                      $modified{$key} = $record->{$version.':'.$key};
                   3367:                  }
                   3368:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3369:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3370:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3371:                 $modified{$key} = $record->{$version.':'.$key};
                   3372:             }
                   3373:         }
                   3374:         if (keys(%modified)) {
                   3375:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3376:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3377:                 $numchanged ++;
                   3378:             }
                   3379:         }
                   3380:     }
                   3381:     return $numchanged;
1.36      ng       3382: }
1.322     albertel 3383: 
1.380     albertel 3384: sub check_and_remove_from_queue {
                   3385:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3386:     my @ungraded_parts;
                   3387:     foreach my $part (@{$parts}) {
                   3388: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3389: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3390: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3391: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3392: 		) {
                   3393: 	    push(@ungraded_parts, $part);
                   3394: 	}
                   3395:     }
                   3396:     if ( !@ungraded_parts ) {
                   3397: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3398: 					       $cnum,$domain,$stuname);
                   3399:     }
                   3400: }
                   3401: 
1.337     banghart 3402: sub handback_files {
                   3403:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3404:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3405:     my $res_error;
                   3406:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3407:     if ($res_error) {
                   3408:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3409:         return;
                   3410:     }
1.654     raeburn  3411:     my @handedback;
                   3412:     my $file_msg;
1.375     albertel 3413:     my @part_response_id = &flatten_responseType($responseType);
                   3414:     foreach my $part_response_id (@part_response_id) {
                   3415:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3416: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3417:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3418:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3419:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3420:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3421:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3422:                     my ($directory,$answer_file) = 
1.654     raeburn  3423:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3424:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3425: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3426: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3427:                     my $getpropath = 1;
1.662     raeburn  3428:                     my ($dir_list,$listerror) = 
                   3429:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3430:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3431: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3432:                     # fix filename
1.355     banghart 3433:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3434:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3435:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3436:             	                                $save_file_name);
1.337     banghart 3437:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3438:                         $request->print('<br /><span class="LC_error">'.
                   3439:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3440:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3441:                                         '</span>');
1.356     banghart 3442:                     } else {
1.360     banghart 3443:                         # mark the file as read only
1.654     raeburn  3444:                         push(@handedback,$save_file_name);
1.367     albertel 3445: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3446: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3447: 			}
                   3448:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3449: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3450:                     }
1.686     bisitz   3451:                     $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 3452:                 }
                   3453:             }
                   3454:         }
1.654     raeburn  3455:     }
                   3456:     if (@handedback > 0) {
                   3457:         $request->print('<br />');
                   3458:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3459:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3460:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3461:         my ($subject,$message);
                   3462:         if (scalar(@handedback) == 1) {
                   3463:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3464:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3465:         } else {
                   3466:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3467:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3468:         }
                   3469:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3470:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3471:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3472:         my ($feedurl,$showsymb) =
                   3473:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3474:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3475:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3476:         my $msgstatus =
                   3477:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3478:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3479:                  $restitle);
                   3480:         if ($msgstatus) {
                   3481:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3482:         }
                   3483:     }
1.338     banghart 3484:     return;
1.337     banghart 3485: }
                   3486: 
1.418     albertel 3487: sub get_feedurl_and_symb {
                   3488:     my ($symb,$uname,$udom) = @_;
                   3489:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3490:     $url = &Apache::lonnet::clutter($url);
                   3491:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3492: 					$symb,$udom,$uname);
                   3493:     if ($encrypturl =~ /^yes$/i) {
                   3494: 	&Apache::lonenc::encrypted(\$url,1);
                   3495: 	&Apache::lonenc::encrypted(\$symb,1);
                   3496:     }
                   3497:     return ($url,$symb);
                   3498: }
                   3499: 
1.313     banghart 3500: sub get_submitted_files {
                   3501:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3502:     my @files;
                   3503:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3504:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3505:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3506:     	    push(@files,$file_url.$file);
                   3507:         }
                   3508:     }
                   3509:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3510:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3511:     }
                   3512:     return (\@files);
                   3513: }
1.322     albertel 3514: 
1.269     raeburn  3515: # ----------- Provides number of tries since last reset.
                   3516: sub get_num_tries {
                   3517:     my ($record,$last_reset,$part) = @_;
                   3518:     my $timestamp = '';
                   3519:     my $num_tries = 0;
                   3520:     if ($$record{'version'}) {
                   3521:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3522:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3523:                 $timestamp = $$record{$version.':timestamp'};
                   3524:                 if ($timestamp > $last_reset) {
                   3525:                     $num_tries ++;
                   3526:                 } else {
                   3527:                     last;
                   3528:                 }
                   3529:             }
                   3530:         }
                   3531:     }
                   3532:     return $num_tries;
                   3533: }
                   3534: 
                   3535: # ----------- Determine decrements required in aggregate totals 
                   3536: sub decrement_aggs {
                   3537:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3538:     my %decrement = (
                   3539:                         attempts => 0,
                   3540:                         users => 0,
                   3541:                         correct => 0
                   3542:                     );
                   3543:     $decrement{'attempts'} = $aggtries;
                   3544:     if ($solvedstatus =~ /^correct/) {
                   3545:         $decrement{'correct'} = 1;
                   3546:     }
                   3547:     if ($aggtries == $totaltries) {
                   3548:         $decrement{'users'} = 1;
                   3549:     }
1.524     raeburn  3550:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3551:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3552:     }
                   3553:     return;
                   3554: }
                   3555: 
                   3556: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3557: sub get_last_resets {
1.270     albertel 3558:     my ($symb,$courseid,$partids) =@_;
                   3559:     my %last_resets;
1.269     raeburn  3560:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3561:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3562:     my @keys;
                   3563:     foreach my $part (@{$partids}) {
                   3564: 	push(@keys,"$symb\0$part\0resettime");
                   3565:     }
                   3566:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3567: 				     $cdom,$cname);
                   3568:     foreach my $part (@{$partids}) {
                   3569: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3570:     }
1.270     albertel 3571:     return %last_resets;
1.269     raeburn  3572: }
                   3573: 
1.251     banghart 3574: # ----------- Handles creating versions for portfolio files as answers
                   3575: sub version_portfiles {
1.343     banghart 3576:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3577:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3578:     my @returned_keys;
1.255     banghart 3579:     my $parts = join('|', @$parts_graded);
1.277     albertel 3580:     foreach my $key (keys(%$record)) {
1.259     banghart 3581:         my $new_portfiles;
1.263     banghart 3582:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3583:             my @versioned_portfiles;
1.367     albertel 3584:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3585:             if (@portfiles) {
                   3586:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3587:                                                       \@versioned_portfiles);
1.252     banghart 3588:             }
1.343     banghart 3589:             $$record{$key} = join(',',@versioned_portfiles);
                   3590:             push(@returned_keys,$key);
1.251     banghart 3591:         }
                   3592:     } 
1.343     banghart 3593:     return (@returned_keys);   
1.305     banghart 3594: }
                   3595: 
1.44      ng       3596: #--------------------------------------------------------------------------------------
                   3597: #
                   3598: #-------------------------- Next few routines handles grading by section or whole class
                   3599: #
                   3600: #--- Javascript to handle grading by section or whole class
1.42      ng       3601: sub viewgrades_js {
                   3602:     my ($request) = shift;
                   3603: 
1.539     riegler  3604:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.736     damieng  3605:     &js_escape(\$alertmsg);
1.597     wenzelju 3606:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3607:    function writePoint(partid,weight,point) {
1.125     ng       3608: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3609: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3610: 	if (point == "textval") {
1.125     ng       3611: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3612: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3613: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3614: 		var resetbox = false;
                   3615: 		for (var i=0; i<radioButton.length; i++) {
                   3616: 		    if (radioButton[i].checked) {
                   3617: 			textbox.value = i;
                   3618: 			resetbox = true;
                   3619: 		    }
                   3620: 		}
                   3621: 		if (!resetbox) {
                   3622: 		    textbox.value = "";
                   3623: 		}
                   3624: 		return;
                   3625: 	    }
1.109     matthew  3626: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3627: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3628: 				   ") greater than the weight for the part. Accept?");
                   3629: 		if (resp == false) {
                   3630: 		    textbox.value = "";
                   3631: 		    return;
                   3632: 		}
                   3633: 	    }
1.42      ng       3634: 	    for (var i=0; i<radioButton.length; i++) {
                   3635: 		radioButton[i].checked=false;
1.109     matthew  3636: 		if (parseFloat(point) == i) {
1.42      ng       3637: 		    radioButton[i].checked=true;
                   3638: 		}
                   3639: 	    }
1.41      ng       3640: 
1.42      ng       3641: 	} else {
1.125     ng       3642: 	    textbox.value = parseFloat(point);
1.42      ng       3643: 	}
1.41      ng       3644: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3645: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3646: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3647: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3648: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3649: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3650: 	    if (saveval != "correct") {
                   3651: 		scorename.value = point;
1.43      ng       3652: 		if (selname[0].selected != true) {
                   3653: 		    selname[0].selected = true;
                   3654: 		}
1.42      ng       3655: 	    }
                   3656: 	}
1.125     ng       3657: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3658:     }
                   3659: 
                   3660:     function writeRadText(partid,weight) {
1.125     ng       3661: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3662: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3663:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3664: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3665: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3666: 	    for (var i=0; i<radioButton.length; i++) {
                   3667: 		radioButton[i].checked=false;
                   3668: 
                   3669: 	    }
                   3670: 	    textbox.value = "";
                   3671: 
                   3672: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3673: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3674: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3675: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3676: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3677: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3678: 		if ((saveval != "correct") || override) {
1.42      ng       3679: 		    scorename.value = "";
1.125     ng       3680: 		    if (selval[1].selected) {
                   3681: 			selname[1].selected = true;
                   3682: 		    } else {
                   3683: 			selname[2].selected = true;
                   3684: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3685: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3686: 		    }
1.42      ng       3687: 		}
                   3688: 	    }
1.43      ng       3689: 	} else {
                   3690: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3691: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3692: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3693: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3694: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3695: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3696: 		if ((saveval != "correct") || override) {
1.125     ng       3697: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3698: 		    selname[0].selected = true;
                   3699: 		}
                   3700: 	    }
                   3701: 	}	    
1.42      ng       3702:     }
                   3703: 
                   3704:     function changeSelect(partid,user) {
1.125     ng       3705: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3706: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3707: 	var point  = textbox.value;
1.125     ng       3708: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3709: 
1.109     matthew  3710: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3711: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3712: 	    textbox.value = "";
                   3713: 	    return;
                   3714: 	}
1.109     matthew  3715: 	if (parseFloat(point) > parseFloat(weight)) {
                   3716: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3717: 			       ") greater than the weight of the part. Accept?");
                   3718: 	    if (resp == false) {
                   3719: 		textbox.value = "";
                   3720: 		return;
                   3721: 	    }
                   3722: 	}
1.42      ng       3723: 	selval[0].selected = true;
                   3724:     }
                   3725: 
                   3726:     function changeOneScore(partid,user) {
1.125     ng       3727: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3728: 	if (selval[1].selected || selval[2].selected) {
                   3729: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3730: 	    if (selval[2].selected) {
                   3731: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3732: 	    }
1.269     raeburn  3733:         }
1.42      ng       3734:     }
                   3735: 
                   3736:     function resetEntry(numpart) {
                   3737: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3738: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3739: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3740: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3741: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3742: 	    for (var i=0; i<radioButton.length; i++) {
                   3743: 		radioButton[i].checked=false;
                   3744: 
                   3745: 	    }
                   3746: 	    textbox.value = "";
                   3747: 	    selval[0].selected = true;
                   3748: 
                   3749: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3750: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3751: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3752: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3753: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3754: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3755: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3756: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3757: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3758: 		if (saveselval == "excused") {
1.43      ng       3759: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3760: 		} else {
1.43      ng       3761: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3762: 		}
                   3763: 	    }
1.41      ng       3764: 	}
1.42      ng       3765:     }
                   3766: 
1.41      ng       3767: VIEWJAVASCRIPT
1.42      ng       3768: }
                   3769: 
1.44      ng       3770: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3771: sub viewgrades {
1.608     www      3772:     my ($request,$symb) = @_;
1.745     raeburn  3773:     my ($is_tool,$toolsymb);
                   3774:     if ($symb =~ /ext\.tool$/) {
                   3775:         $is_tool = 1;
                   3776:         $toolsymb = $symb;
                   3777:     }
1.42      ng       3778:     &viewgrades_js($request);
1.41      ng       3779: 
1.168     albertel 3780:     #need to make sure we have the correct data for later EXT calls, 
                   3781:     #thus invalidate the cache
                   3782:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3783:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3784:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3785:     &Apache::lonnet::clear_EXT_cache_status();
                   3786: 
1.398     albertel 3787:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3788: 
                   3789:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3790:     $result.=&jscriptNform($symb);
1.41      ng       3791: 
1.44      ng       3792:     #beginning of class grading form
1.442     banghart 3793:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3794:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3795: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3796: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3797: 	&build_section_inputs().
1.442     banghart 3798: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3799: 
1.738     raeburn  3800:     #retrieve selected groups
                   3801:     my (@groups,$group_display);
                   3802:     @groups = &Apache::loncommon::get_env_multiple('form.group');
                   3803:     if (grep(/^all$/,@groups)) {
                   3804:         @groups = ('all');
                   3805:     } elsif (grep(/^none$/,@groups)) {
                   3806:         @groups = ('none');
                   3807:     } elsif (@groups > 0) {
                   3808:         $group_display = join(', ',@groups);
                   3809:     }
                   3810: 
                   3811:     my ($common_header,$specific_header,@sections,$section_display);
                   3812:     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3813:     if (grep(/^all$/,@sections)) {
                   3814:         @sections = ('all');
                   3815:         if ($group_display) {
                   3816:             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3817:             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3818:         } elsif (grep(/^none$/,@groups)) {
                   3819:             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3820:             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3821:         } else {
                   3822: 	    $common_header = &mt('Assign Common Grade to Class');
                   3823:             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3824:         }
                   3825:     } elsif (grep(/^none$/,@sections)) {
                   3826:         @sections = ('none');
                   3827:         if ($group_display) {
                   3828:             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3829:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3830:         } elsif (grep(/^none$/,@groups)) {
                   3831:             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3832:             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3833:         } else {
                   3834:             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3835: 	    $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3836:         }
                   3837:     } else {
                   3838:         $section_display = join (", ",@sections);
                   3839:         if ($group_display) {
                   3840:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3841:                                  $section_display,$group_display);
                   3842:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3843:                                    $section_display,$group_display);
                   3844:         } elsif (grep(/^none$/,@groups)) {
                   3845:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3846:             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3847:         } else {
                   3848:             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3849: 	    $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3850:         }
                   3851:     }
                   3852:     my %submit_types = &substatus_options();
                   3853:     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3854: 
                   3855:     if ($env{'form.submitonly'} eq 'all') {
                   3856:         $result.= '<h3>'.$common_header.'</h3>';
                   3857:     } else {
1.745     raeburn  3858:         my $text;
                   3859:         if ($is_tool) {
                   3860:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3861:         } else {
                   3862:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3863:         }
                   3864:         $result.= '<h3>'.$common_header.'&nbsp;'.$text.'</h3>';
1.52      albertel 3865:     }
1.738     raeburn  3866:     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3867:     #radio buttons/text box for assigning points for a section or class.
                   3868:     #handles different parts of a problem
1.582     raeburn  3869:     my $res_error;
                   3870:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3871:     if ($res_error) {
                   3872:         return &navmap_errormsg();
                   3873:     }
1.42      ng       3874:     my %weight = ();
                   3875:     my $ctsparts = 0;
1.45      ng       3876:     my %seen = ();
1.745     raeburn  3877:     my @part_response_id;
                   3878:     if ($is_tool) {
                   3879:         @part_response_id = ([0,'']);
                   3880:     } else {
                   3881:         @part_response_id = &flatten_responseType($responseType);
                   3882:     }
1.375     albertel 3883:     foreach my $part_response_id (@part_response_id) {
                   3884:     	my ($partid,$respid) = @{ $part_response_id };
                   3885: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3886: 	next if $seen{$partid};
                   3887: 	$seen{$partid}++;
1.744     raeburn  3888: #	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3889: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3890: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3891: 
1.324     albertel 3892: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3893: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3894: 	my $ctr = 0;
1.42      ng       3895: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3896: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3897: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3898: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3899: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3900: 	    $ctr++;
                   3901: 	}
1.485     albertel 3902: 	$radio.='</tr></table>';
                   3903: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3904: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3905: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3906: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3907:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3908:             '<select name="SELVAL_'.$partid.'" '.
                   3909:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3910:                 $weight{$partid}.')"> '.
1.401     albertel 3911: 	    '<option selected="selected"> </option>'.
1.485     albertel 3912: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3913: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3914: 	    '</select></td>'.
                   3915:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3916: 	$line.='<input type="hidden" name="partid_'.
                   3917: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3918: 	$line.='<input type="hidden" name="weight_'.
                   3919: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3920: 
                   3921: 	$result.=
                   3922: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3923: 	    '<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 3924: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3925: 	$ctsparts++;
1.41      ng       3926:     }
1.474     albertel 3927:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3928: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3929:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3930: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3931: 
1.44      ng       3932:     #table listing all the students in a section/class
                   3933:     #header of table
1.738     raeburn  3934:     if ($env{'form.submitonly'} eq 'all') {
                   3935:         $result.= '<h3>'.$specific_header.'</h3>';
                   3936:     } else {
1.745     raeburn  3937:         my $text;
                   3938:         if ($is_tool) {
                   3939:             $text = &mt('(transaction status: "[_1]")',$submission_status);
                   3940:         } else {
                   3941:             $text = &mt('(submission status: "[_1]")',$submission_status);
                   3942:         }
                   3943:         $result.= '<h3>'.$specific_header.'&nbsp;'.$text.'</h3>';
1.738     raeburn  3944:     }
                   3945:     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3946: 	      &Apache::loncommon::start_data_table_header_row().
                   3947: 	      '<th>'.&mt('No.').'</th>'.
                   3948: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3949:     my $partserror;
                   3950:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3951:     if ($partserror) {
                   3952:         return &navmap_errormsg();
                   3953:     }
1.324     albertel 3954:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3955:     my @partids = ();
1.41      ng       3956:     foreach my $part (@parts) {
1.745     raeburn  3957: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.539     riegler  3958:         my $narrowtext = &mt('Tries');
                   3959: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.745     raeburn  3960: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
1.207     albertel 3961: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3962:         push(@partids,$partid);
1.628     www      3963: #
                   3964: # FIXME: Looks like $display looks at English text
                   3965: #
1.324     albertel 3966: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3967: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3968: 	    $result.='<th>'.
1.697     bisitz   3969: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3970: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3971: 	    next;
1.485     albertel 3972: 	    
1.207     albertel 3973: 	} else {
1.485     albertel 3974: 	    if ($display =~ /Problem Status/) {
                   3975: 		my $grade_status_mt = &mt('Grade Status');
                   3976: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3977: 	    }
                   3978: 	    my $part_mt = &mt('Part:');
                   3979: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3980: 	}
1.485     albertel 3981: 
1.474     albertel 3982: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3983:     }
1.474     albertel 3984:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3985: 
1.270     albertel 3986:     my %last_resets = 
                   3987: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3988: 
1.41      ng       3989:     #get info for each student
1.44      ng       3990:     #list all the students - with points and grade status
1.738     raeburn  3991:     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3992:     my $ctr = 0;
1.294     albertel 3993:     foreach (sort 
                   3994: 	     {
                   3995: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3996: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3997: 		 }
                   3998: 		 return $a cmp $b;
                   3999: 	     } (keys(%$fullname))) {
1.324     albertel 4000: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.745     raeburn  4001: 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
1.41      ng       4002:     }
1.474     albertel 4003:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       4004:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 4005:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   4006: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.738     raeburn  4007:     if ($ctr == 0) {
1.442     banghart 4008:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.738     raeburn  4009:         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   4010:                 '<span class="LC_warning">';
                   4011:         if ($env{'form.submitonly'} eq 'all') {
                   4012:             if (grep(/^all$/,@sections)) {
                   4013:                 if (grep(/^all$/,@groups)) {
                   4014:                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   4015:                                    $stu_status);
                   4016:                 } elsif (grep(/^none$/,@groups)) {
                   4017:                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   4018:                                    $stu_status); 
                   4019:                 } else {
                   4020:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4021:                                    $group_display,$stu_status);
                   4022:                 }
                   4023:             } elsif (grep(/^none$/,@sections)) {
                   4024:                 if (grep(/^all$/,@groups)) {
                   4025:                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   4026:                                    $stu_status);
                   4027:                 } elsif (grep(/^none$/,@groups)) {
                   4028:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   4029:                                    $stu_status);
                   4030:                 } else {
                   4031:                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   4032:                                    $group_display,$stu_status);
                   4033:                 }
                   4034:             } else {
                   4035:                 if (grep(/^all$/,@groups)) {
                   4036:                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   4037:                                    $section_display,$stu_status);
                   4038:                 } elsif (grep(/^none$/,@groups)) {
1.739     raeburn  4039:                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
1.738     raeburn  4040:                                    $section_display,$stu_status);
                   4041:                 } else {
                   4042:                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   4043:                                    $section_display,$group_display,$stu_status);
                   4044:                 }
                   4045:             }
                   4046:         } else {
                   4047:             if (grep(/^all$/,@sections)) {
                   4048:                 if (grep(/^all$/,@groups)) {
                   4049:                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4050:                                    $stu_status,$submission_status);
                   4051:                 } elsif (grep(/^none$/,@groups)) {
                   4052:                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4053:                                    $stu_status,$submission_status);
                   4054:                 } else {
                   4055:                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4056:                                    $group_display,$stu_status,$submission_status);
                   4057:                 }
                   4058:             } elsif (grep(/^none$/,@sections)) {
                   4059:                 if (grep(/^all$/,@groups)) {
                   4060:                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4061:                                    $stu_status,$submission_status);
                   4062:                 } elsif (grep(/^none$/,@groups)) {
                   4063:                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4064:                                    $stu_status,$submission_status);
                   4065:                 } else {
                   4066:                     $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.',
                   4067:                                    $group_display,$stu_status,$submission_status);
                   4068:                 }
                   4069:             } else {
                   4070:                 if (grep(/^all$/,@groups)) {
                   4071: 	            $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4072: 	                           $section_display,$stu_status,$submission_status);
                   4073:                 } elsif (grep(/^none$/,@groups)) {
                   4074:                     $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.',
                   4075:                                    $section_display,$stu_status,$submission_status);
                   4076:                 } else {
                   4077:                     $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.',
                   4078:                                    $section_display,$group_display,$stu_status,$submission_status);
                   4079:                 }
                   4080:             }
                   4081:         }
                   4082: 	$result .= '</span><br />';
1.96      albertel 4083:     }
1.41      ng       4084:     return $result;
                   4085: }
                   4086: 
1.738     raeburn  4087: #--- call by previous routine to display each student who satisfies submission filter. 
1.41      ng       4088: sub viewstudentgrade {
1.745     raeburn  4089:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
1.44      ng       4090:     my ($uname,$udom) = split(/:/,$student);
                   4091:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.738     raeburn  4092:     my $submitonly = $env{'form.submitonly'};
                   4093:     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4094:         my %partstatus = ();
                   4095:         if (ref($parts) eq 'ARRAY') {
                   4096:             foreach my $apart (@{$parts}) {
                   4097:                 my ($part,$type) = &split_part_type($apart);
                   4098:                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4099:                 $status = 'nothing' if ($status eq '');
                   4100:                 $partstatus{$part}      = $status;
                   4101:                 my $subkey = "resource.$part.submitted_by";
                   4102:                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4103:             }
                   4104:             my $submitted = 0;
                   4105:             my $graded = 0;
                   4106:             my $incorrect = 0;
                   4107:             foreach my $key (keys(%partstatus)) {
                   4108:                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4109:                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4110:                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4111: 
                   4112:                 my $partid = (split(/\./,$key))[1];
                   4113:                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4114:                     $submitted = 0;
                   4115:                 }
                   4116:             }
                   4117:             return if (!$submitted && ($submitonly eq 'yes' ||
                   4118:                                        $submitonly eq 'incorrect' ||
                   4119:                                        $submitonly eq 'graded'));
                   4120:             return if (!$graded && ($submitonly eq 'graded'));
                   4121:             return if (!$incorrect && $submitonly eq 'incorrect');
                   4122:         }
                   4123:     }
                   4124:     if ($submitonly eq 'queued') {
                   4125:         my ($cdom,$cnum) = split(/_/,$courseid);
                   4126:         my %queue_status =
                   4127:             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4128:                                                     $udom,$uname);
                   4129:         return if (!defined($queue_status{'gradingqueue'}));
                   4130:     }
                   4131:     $$ctr++;
                   4132:     my %aggregates = ();
1.474     albertel 4133:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.738     raeburn  4134: 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4135: 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4136: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4137: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4138: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4139:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4140:     foreach my $apart (@$parts) {
                   4141: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4142: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4143:         $result.='<td align="center">';
1.269     raeburn  4144:         my ($aggtries,$totaltries);
                   4145:         unless (exists($aggregates{$part})) {
1.270     albertel 4146: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4147: 	    $aggtries = $totaltries;
1.269     raeburn  4148:             if ($$last_resets{$part}) {  
1.270     albertel 4149:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4150: 					   $part);
                   4151:             }
1.269     raeburn  4152:             $result.='<input type="hidden" name="'.
                   4153:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4154:             $result.='<input type="hidden" name="'.
                   4155:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4156:             $aggregates{$part} = 1;
                   4157:         }
1.41      ng       4158: 	if ($type eq 'awarded') {
1.320     albertel 4159: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4160: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4161: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4162: 	    $result.='<input type="text" name="'.
1.89      albertel 4163: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4164:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4165: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4166: 	} elsif ($type eq 'solved') {
                   4167: 	    my ($status,$foo)=split(/_/,$score,2);
                   4168: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4169: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4170: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4171: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4172: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4173:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4174: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4175: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4176: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4177: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4178: 	} else {
                   4179: 	    $result.='<input type="hidden" name="'.
                   4180: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4181: 		    "\n";
1.233     albertel 4182: 	    $result.='<input type="text" name="'.
1.122     ng       4183: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4184: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4185: 	}
                   4186:     }
1.474     albertel 4187:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4188:     return $result;
1.38      ng       4189: }
                   4190: 
1.44      ng       4191: #--- change scores for all the students in a section/class
                   4192: #    record does not get update if unchanged
1.38      ng       4193: sub editgrades {
1.608     www      4194:     my ($request,$symb) = @_;
1.745     raeburn  4195:     my $toolsymb;
                   4196:     if ($symb =~ /ext\.tool$/) {
                   4197:         $toolsymb = $symb;
                   4198:     }
1.41      ng       4199: 
1.433     banghart 4200:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4201:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 4202:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       4203: 
1.477     albertel 4204:     my $result= &Apache::loncommon::start_data_table().
                   4205: 	&Apache::loncommon::start_data_table_header_row().
                   4206: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4207: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4208:     my %scoreptr = (
                   4209: 		    'correct'  =>'correct_by_override',
                   4210: 		    'incorrect'=>'incorrect_by_override',
                   4211: 		    'excused'  =>'excused',
                   4212: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4213:                     'credited' =>'credit_attempted',
1.43      ng       4214: 		    'nothing'  => '',
                   4215: 		    );
1.257     albertel 4216:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4217: 
1.44      ng       4218:     my (@partid);
                   4219:     my %weight = ();
1.54      albertel 4220:     my %columns = ();
1.44      ng       4221:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4222: 
1.582     raeburn  4223:     my $partserror;
                   4224:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4225:     if ($partserror) {
                   4226:         return &navmap_errormsg();
                   4227:     }
1.54      albertel 4228:     my $header;
1.257     albertel 4229:     while ($ctr < $env{'form.totalparts'}) {
                   4230: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4231: 	push(@partid,$partid);
1.257     albertel 4232: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4233: 	$ctr++;
1.54      albertel 4234:     }
1.324     albertel 4235:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.748     raeburn  4236:     my $totcolspan = 0;
1.54      albertel 4237:     foreach my $partid (@partid) {
1.478     albertel 4238: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4239: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4240: 	$columns{$partid}=2;
                   4241: 	foreach my $stores (@parts) {
                   4242: 	    my ($part,$type) = &split_part_type($stores);
                   4243: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4244: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
1.745     raeburn  4245: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
1.551     raeburn  4246: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4247:             my $narrowtext = &mt('Tries');
                   4248: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4249: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4250: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4251: 	    $columns{$partid}+=2;
                   4252: 	}
1.748     raeburn  4253:         $totcolspan += $columns{$partid};
1.54      albertel 4254:     }
                   4255:     foreach my $partid (@partid) {
1.324     albertel 4256: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4257: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4258: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4259: 	    '</th>';
1.54      albertel 4260: 
1.44      ng       4261:     }
1.477     albertel 4262:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4263: 	&Apache::loncommon::start_data_table_header_row().
                   4264: 	$header.
                   4265: 	&Apache::loncommon::end_data_table_header_row();
                   4266:     my @noupdate;
1.126     ng       4267:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4268:     for ($i=0; $i<$env{'form.total'}; $i++) {
                   4269: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4270: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4271: 	my %newrecord;
                   4272: 	my $updateflag = 0;
1.108     albertel 4273: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.748     raeburn  4274: 	my $canmodify = &canmodify($usec);
                   4275: 	my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
                   4276: 		   &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
                   4277: 	if (!$canmodify) {
1.477     albertel 4278: 	    push(@noupdate,
1.748     raeburn  4279: 		 $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
                   4280: 		 &mt('Not allowed to modify student')."</span></td>");
1.105     albertel 4281: 	    next;
                   4282: 	}
1.269     raeburn  4283:         my %aggregate = ();
                   4284:         my $aggregateflag = 0;
1.281     albertel 4285: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4286: 	foreach (@partid) {
1.257     albertel 4287: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4288: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4289: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4290: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4291: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4292: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4293: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4294: 	    my $score;
                   4295: 	    if ($partial eq '') {
1.257     albertel 4296: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4297: 	    } elsif ($partial > 0) {
                   4298: 		$score = 'correct_by_override';
                   4299: 	    } elsif ($partial == 0) {
                   4300: 		$score = 'incorrect_by_override';
                   4301: 	    }
1.257     albertel 4302: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4303: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4304: 
1.292     albertel 4305: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4306: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4307: 	    if ($dropMenu eq 'reset status' &&
                   4308: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4309: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4310: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4311: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4312: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4313: 		$updateflag = 1;
1.269     raeburn  4314:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4315:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4316:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4317:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4318:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4319:                     $aggregateflag = 1;
                   4320:                 }
1.139     albertel 4321: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4322: 		$updateflag = 1;
                   4323: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4324: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4325: 		$rec_update++;
1.125     ng       4326: 	    }
                   4327: 
1.93      albertel 4328: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4329: 		'<td align="center">'.$awarded.
                   4330: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4331: 
1.54      albertel 4332: 
                   4333: 	    my $partid=$_;
                   4334: 	    foreach my $stores (@parts) {
                   4335: 		my ($part,$type) = &split_part_type($stores);
                   4336: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4337: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4338: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4339: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4340: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4341: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4342: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4343: 		    $updateflag=1;
                   4344: 		}
1.93      albertel 4345: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4346: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4347: 	    }
1.44      ng       4348: 	}
1.477     albertel 4349: 	$line.="\n";
1.301     albertel 4350: 
                   4351: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4352: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4353: 
1.44      ng       4354: 	if ($updateflag) {
                   4355: 	    $count++;
1.257     albertel 4356: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4357: 				    $udom,$uname);
1.301     albertel 4358: 
                   4359: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4360: 					      $cnum,$udom,$uname)) {
                   4361: 		# need to figure out if should be in queue.
                   4362: 		my %record =  
                   4363: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4364: 					     $udom,$uname);
                   4365: 		my $all_graded = 1;
                   4366: 		my $none_graded = 1;
                   4367: 		foreach my $part (@parts) {
                   4368: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4369: 			$all_graded = 0;
                   4370: 		    } else {
                   4371: 			$none_graded = 0;
                   4372: 		    }
                   4373: 		}
                   4374: 
                   4375: 		if ($all_graded || $none_graded) {
                   4376: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4377: 							   $symb,$cdom,$cnum,
                   4378: 							   $udom,$uname);
                   4379: 		}
                   4380: 	    }
                   4381: 
1.477     albertel 4382: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4383: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4384: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4385: 	    $updateCtr++;
1.93      albertel 4386: 	} else {
1.477     albertel 4387: 	    push(@noupdate,
                   4388: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4389: 	    $noupdateCtr++;
1.44      ng       4390: 	}
1.269     raeburn  4391:         if ($aggregateflag) {
                   4392:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4393: 				  $cdom,$cnum);
1.269     raeburn  4394:         }
1.93      albertel 4395:     }
1.477     albertel 4396:     if (@noupdate) {
1.748     raeburn  4397:         my $numcols=$totcolspan+2;
1.477     albertel 4398: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4399: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4400: 	    &mt('No Changes Occurred For the Students Below').
                   4401: 	    '</td>'.
1.477     albertel 4402: 	    &Apache::loncommon::end_data_table_row();
                   4403: 	foreach my $line (@noupdate) {
                   4404: 	    $result.=
                   4405: 		&Apache::loncommon::start_data_table_row().
                   4406: 		$line.
                   4407: 		&Apache::loncommon::end_data_table_row();
                   4408: 	}
1.44      ng       4409:     }
1.614     www      4410:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4411:     my $msg = '<p><b>'.
                   4412: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4413: 	    $rec_update,$count).'</b><br />'.
                   4414: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4415: 	'</b></p>';
1.44      ng       4416:     return $title.$msg.$result;
1.5       albertel 4417: }
1.54      albertel 4418: 
                   4419: sub split_part_type {
                   4420:     my ($partstr) = @_;
                   4421:     my ($temp,@allparts)=split(/_/,$partstr);
                   4422:     my $type=pop(@allparts);
1.439     albertel 4423:     my $part=join('_',@allparts);
1.54      albertel 4424:     return ($part,$type);
                   4425: }
                   4426: 
1.44      ng       4427: #------------- end of section for handling grading by section/class ---------
                   4428: #
                   4429: #----------------------------------------------------------------------------
                   4430: 
1.5       albertel 4431: 
1.44      ng       4432: #----------------------------------------------------------------------------
                   4433: #
                   4434: #-------------------------- Next few routines handles grading by csv upload
                   4435: #
                   4436: #--- Javascript to handle csv upload
1.27      albertel 4437: sub csvupload_javascript_reverse_associate {
1.743     raeburn  4438:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4439:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4440:   &js_escape(\$error1);
                   4441:   &js_escape(\$error2);
1.27      albertel 4442:   return(<<ENDPICK);
                   4443:   function verify(vf) {
                   4444:     var foundsomething=0;
                   4445:     var founduname=0;
1.243     albertel 4446:     var foundID=0;
1.743     raeburn  4447:     var foundclicker=0;
1.27      albertel 4448:     for (i=0;i<=vf.nfields.value;i++) {
                   4449:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4450:       if (i==0 && tw!=0) { foundID=1; }
                   4451:       if (i==1 && tw!=0) { founduname=1; }
1.743     raeburn  4452:       if (i==2 && tw!=0) { foundclicker=1; }
                   4453:       if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
1.27      albertel 4454:     }
1.743     raeburn  4455:     if (founduname==0 && foundID==0 && foundclicker==0) {
1.246     albertel 4456: 	alert('$error1');
                   4457: 	return;
1.27      albertel 4458:     }
                   4459:     if (foundsomething==0) {
1.246     albertel 4460: 	alert('$error2');
                   4461: 	return;
1.27      albertel 4462:     }
                   4463:     vf.submit();
                   4464:   }
                   4465:   function flip(vf,tf) {
                   4466:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4467:     var i;
                   4468:     for (i=0;i<=vf.nfields.value;i++) {
                   4469:       //can not pick the same destination field for both name and domain
                   4470:       if (((i ==0)||(i ==1)) && 
                   4471:           ((tf==0)||(tf==1)) && 
                   4472:           (i!=tf) &&
                   4473:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4474:         eval('vf.f'+i+'.selectedIndex=0;')
                   4475:       }
                   4476:     }
                   4477:   }
                   4478: ENDPICK
                   4479: }
                   4480: 
                   4481: sub csvupload_javascript_forward_associate {
1.743     raeburn  4482:     my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
1.246     albertel 4483:     my $error2=&mt('You need to specify at least one grading field');
1.736     damieng  4484:   &js_escape(\$error1);
                   4485:   &js_escape(\$error2);
1.27      albertel 4486:   return(<<ENDPICK);
                   4487:   function verify(vf) {
                   4488:     var foundsomething=0;
                   4489:     var founduname=0;
1.243     albertel 4490:     var foundID=0;
1.743     raeburn  4491:     var foundclicker=0;
1.27      albertel 4492:     for (i=0;i<=vf.nfields.value;i++) {
                   4493:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4494:       if (tw==1) { foundID=1; }
                   4495:       if (tw==2) { founduname=1; }
1.745     raeburn  4496:       if (tw==3) { foundclicker=1; }
1.743     raeburn  4497:       if (tw>4) { foundsomething=1; }
1.27      albertel 4498:     }
1.743     raeburn  4499:     if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
1.246     albertel 4500: 	alert('$error1');
                   4501: 	return;
1.27      albertel 4502:     }
                   4503:     if (foundsomething==0) {
1.246     albertel 4504: 	alert('$error2');
                   4505: 	return;
1.27      albertel 4506:     }
                   4507:     vf.submit();
                   4508:   }
                   4509:   function flip(vf,tf) {
                   4510:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4511:     var i;
                   4512:     //can not pick the same destination field twice
                   4513:     for (i=0;i<=vf.nfields.value;i++) {
                   4514:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4515:         eval('vf.f'+i+'.selectedIndex=0;')
                   4516:       }
                   4517:     }
                   4518:   }
                   4519: ENDPICK
                   4520: }
                   4521: 
1.26      albertel 4522: sub csvuploadmap_header {
1.324     albertel 4523:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4524:     my $javascript;
1.257     albertel 4525:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4526: 	$javascript=&csvupload_javascript_reverse_associate();
                   4527:     } else {
                   4528: 	$javascript=&csvupload_javascript_forward_associate();
                   4529:     }
1.45      ng       4530: 
1.418     albertel 4531:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4532:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4533:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4534:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4535:     my $reverse=&mt("Reverse Association");
1.41      ng       4536:     $request->print(<<ENDPICK);
1.632     www      4537: <br />
                   4538: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4539: <input type="hidden" name="associate"  value="" />
                   4540: <input type="hidden" name="phase"      value="three" />
                   4541: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4542: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4543: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4544: <input type="hidden" name="upfile_associate" 
1.257     albertel 4545:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4546: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4547: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4548: <hr />
                   4549: ENDPICK
1.597     wenzelju 4550:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4551:     return '';
1.26      albertel 4552: 
                   4553: }
                   4554: 
                   4555: sub csvupload_fields {
1.582     raeburn  4556:     my ($symb,$errorref) = @_;
1.745     raeburn  4557:     my $toolsymb;
                   4558:     if ($symb =~ /ext\.tool$/) {
                   4559:         $toolsymb = $symb;
                   4560:     }
1.582     raeburn  4561:     my (@parts) = &getpartlist($symb,$errorref);
                   4562:     if (ref($errorref)) {
                   4563:         if ($$errorref) {
                   4564:             return;
                   4565:         }
                   4566:     }
                   4567: 
1.556     weissno  4568:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4569: 		['username','Student Username'],
1.743     raeburn  4570: 		['clicker','Clicker ID'],
1.243     albertel 4571: 		['domain','Student Domain']);
1.324     albertel 4572:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4573:     foreach my $part (sort(@parts)) {
                   4574: 	my @datum;
1.745     raeburn  4575: 	my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
1.41      ng       4576: 	my $name=$part;
1.745     raeburn  4577: 	if (!$display) { $display = $name; }
1.41      ng       4578: 	@datum=($name,$display);
1.244     albertel 4579: 	if ($name=~/^stores_(.*)_awarded/) {
                   4580: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4581: 	}
1.41      ng       4582: 	push(@fields,\@datum);
                   4583:     }
                   4584:     return (@fields);
1.26      albertel 4585: }
                   4586: 
                   4587: sub csvuploadmap_footer {
1.41      ng       4588:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4589:     my $buttontext = &mt('Assign Grades');
1.41      ng       4590:     $request->print(<<ENDPICK);
1.26      albertel 4591: </table>
                   4592: <input type="hidden" name="nfields" value="$i" />
                   4593: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4594: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4595: </form>
                   4596: ENDPICK
                   4597: }
                   4598: 
1.283     albertel 4599: sub checkforfile_js {
1.638     www      4600:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  4601:     &js_escape(\$alertmsg);
1.597     wenzelju 4602:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4603:     function checkUpload(formname) {
                   4604: 	if (formname.upfile.value == "") {
1.539     riegler  4605: 	    alert("$alertmsg");
1.86      ng       4606: 	    return false;
                   4607: 	}
                   4608: 	formname.submit();
                   4609:     }
                   4610: CSVFORMJS
1.283     albertel 4611:     return $result;
                   4612: }
                   4613: 
                   4614: sub upcsvScores_form {
1.608     www      4615:     my ($request,$symb) = @_;
1.283     albertel 4616:     if (!$symb) {return '';}
                   4617:     my $result=&checkforfile_js();
1.632     www      4618:     $result.=&Apache::loncommon::start_data_table().
                   4619:              &Apache::loncommon::start_data_table_header_row().
                   4620:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4621:              &Apache::loncommon::end_data_table_header_row().
                   4622:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4623:     my $upload=&mt("Upload Scores");
1.86      ng       4624:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4625:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4626:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4627:     $result.=<<ENDUPFORM;
1.106     albertel 4628: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4629: <input type="hidden" name="symb" value="$symb" />
                   4630: <input type="hidden" name="command" value="csvuploadmap" />
                   4631: $upfile_select
1.589     bisitz   4632: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4633: </form>
                   4634: ENDUPFORM
1.370     www      4635:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4636:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4637:              '</td>'.
                   4638:             &Apache::loncommon::end_data_table_row().
                   4639:             &Apache::loncommon::end_data_table();
1.86      ng       4640:     return $result;
                   4641: }
                   4642: 
                   4643: 
1.26      albertel 4644: sub csvuploadmap {
1.608     www      4645:     my ($request,$symb)= @_;
1.41      ng       4646:     if (!$symb) {return '';}
1.72      ng       4647: 
1.41      ng       4648:     my $datatoken;
1.257     albertel 4649:     if (!$env{'form.datatoken'}) {
1.41      ng       4650: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4651:     } else {
1.742     raeburn  4652: 	$datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4653:         if ($datatoken ne '') {
                   4654: 	    &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4655:         }
1.26      albertel 4656:     }
1.41      ng       4657:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4658:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4659:     my ($i,$keyfields);
                   4660:     if (@records) {
1.582     raeburn  4661:         my $fieldserror;
                   4662: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4663:         if ($fieldserror) {
                   4664:             $request->print(&navmap_errormsg());
                   4665:             return;
                   4666:         }
1.257     albertel 4667: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4668: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4669: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4670: 							  \@fields);
                   4671: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4672: 	    chop($keyfields);
                   4673: 	} else {
                   4674: 	    unshift(@fields,['none','']);
                   4675: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4676: 							    \@fields);
1.311     banghart 4677:             foreach my $rec (@records) {
                   4678:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4679:                 if (%temp) {
                   4680:                     $keyfields=join(',',sort(keys(%temp)));
                   4681:                     last;
                   4682:                 }
                   4683:             }
1.41      ng       4684: 	}
                   4685:     }
                   4686:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4687: 
1.41      ng       4688:     return '';
1.27      albertel 4689: }
                   4690: 
1.246     albertel 4691: sub csvuploadoptions {
1.608     www      4692:     my ($request,$symb)= @_;
1.632     www      4693:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4694:     $request->print(<<ENDPICK);
                   4695: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4696: <input type="hidden" name="command"    value="csvuploadassign" />
                   4697: <p>
                   4698: <label>
                   4699:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4700:    $overwrite
1.246     albertel 4701: </label>
                   4702: </p>
                   4703: ENDPICK
                   4704:     my %fields=&get_fields();
                   4705:     if (!defined($fields{'domain'})) {
1.257     albertel 4706: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4707: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4708:     }
1.257     albertel 4709:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4710: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4711: 	my $cleankey=$1;
                   4712: 	if ($cleankey eq 'command') { next; }
                   4713: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4714: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4715:     }
                   4716:     # FIXME do a check for any duplicated user ids...
                   4717:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4718:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4719: <hr /></form>'."\n");
1.246     albertel 4720:     return '';
                   4721: }
                   4722: 
                   4723: sub get_fields {
                   4724:     my %fields;
1.257     albertel 4725:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4726:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4727: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4728: 	    if ($env{'form.f'.$i} ne 'none') {
                   4729: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4730: 	    }
                   4731: 	} else {
1.257     albertel 4732: 	    if ($env{'form.f'.$i} ne 'none') {
                   4733: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4734: 	    }
                   4735: 	}
1.27      albertel 4736:     }
1.246     albertel 4737:     return %fields;
                   4738: }
                   4739: 
                   4740: sub csvuploadassign {
1.608     www      4741:     my ($request,$symb)= @_;
1.246     albertel 4742:     if (!$symb) {return '';}
1.345     bowersj2 4743:     my $error_msg = '';
1.742     raeburn  4744:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
                   4745:     if ($datatoken ne '') { 
                   4746:         &Apache::loncommon::load_tmp_file($request,$datatoken);
                   4747:     }
1.246     albertel 4748:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4749:     my %fields=&get_fields();
1.257     albertel 4750:     my $courseid=$env{'request.course.id'};
1.97      albertel 4751:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4752:     my @notallowed;
1.41      ng       4753:     my @skipped;
1.657     raeburn  4754:     my @warnings;
1.41      ng       4755:     my $countdone=0;
                   4756:     foreach my $grade (@gradedata) {
                   4757: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4758: 	my $domain;
                   4759: 	if ($entries{$fields{'domain'}}) {
                   4760: 	    $domain=$entries{$fields{'domain'}};
                   4761: 	} else {
1.257     albertel 4762: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4763: 	}
1.243     albertel 4764: 	$domain=~s/\s//g;
1.41      ng       4765: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4766: 	$username=~s/\s//g;
1.243     albertel 4767: 	if (!$username) {
                   4768: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4769: 	    $id=~s/\s//g;
1.737     raeburn  4770:             if ($id ne '') {
                   4771: 	        my %ids=&Apache::lonnet::idget($domain,[$id]);
                   4772: 	        $username=$ids{$id};
                   4773:             } else {
                   4774:                 if ($entries{$fields{'clicker'}}) {
                   4775:                     my $clicker = $entries{$fields{'clicker'}};
                   4776:                     $clicker=~s/\s//g;
                   4777:                     if ($clicker ne '') {
                   4778:                         my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
                   4779:                         if ($clickers{$clicker} ne '') {  
                   4780:                             my $match = 0;
                   4781:                             my @inclass;
                   4782:                             foreach my $poss (split(/,/,$clickers{$clicker})) {
                   4783:                                 if (exists($$classlist{"$poss:$domain"})) {
                   4784:                                     $username = $poss;
                   4785:                                     push(@inclass,$poss);
                   4786:                                     $match ++;
                   4787:                                     
                   4788:                                 }
                   4789:                             }
                   4790:                             if ($match > 1) {
                   4791:                                 undef($username); 
                   4792:                                 $request->print('<p class="LC_warning">'.
                   4793:                                                 &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
                   4794:                                                 $clicker,join(', ',@inclass)).'</p>');
                   4795:                             }
                   4796:                         }
                   4797:                     }
                   4798:                 }
                   4799:             }
1.243     albertel 4800: 	}
1.41      ng       4801: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4802: 	    my $id=$entries{$fields{'ID'}};
                   4803: 	    $id=~s/\s//g;
1.737     raeburn  4804:             my $clicker = $entries{$fields{'clicker'}};
                   4805:             $clicker=~s/\s//g;
                   4806:             if ($clicker) {
                   4807:                 push(@skipped,"$clicker:$domain");
                   4808: 	    } elsif ($id) {
1.247     albertel 4809: 		push(@skipped,"$id:$domain");
                   4810: 	    } else {
                   4811: 		push(@skipped,"$username:$domain");
                   4812: 	    }
1.41      ng       4813: 	    next;
                   4814: 	}
1.108     albertel 4815: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4816: 	if (!&canmodify($usec)) {
                   4817: 	    push(@notallowed,"$username:$domain");
                   4818: 	    next;
                   4819: 	}
1.244     albertel 4820: 	my %points;
1.41      ng       4821: 	my %grades;
                   4822: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4823: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4824: 		$dest eq 'domain') { next; }
                   4825: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4826: 	    if ($dest=~/stores_(.*)_points/) {
                   4827: 		my $part=$1;
                   4828: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4829: 					      $symb,$domain,$username);
1.345     bowersj2 4830:                 if ($wgt) {
                   4831:                     $entries{$fields{$dest}}=~s/\s//g;
                   4832:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4833:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4834:                                           : 'correct_by_override';
1.638     www      4835:                     if ($pcr>1) {
1.657     raeburn  4836:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4837:                     }
1.345     bowersj2 4838:                     $grades{"resource.$part.awarded"}=$pcr;
                   4839:                     $grades{"resource.$part.solved"}=$award;
                   4840:                     $points{$part}=1;
                   4841:                 } else {
                   4842:                     $error_msg = "<br />" .
                   4843:                         &mt("Some point values were assigned"
                   4844:                             ." for problems with a weight "
                   4845:                             ."of zero. These values were "
                   4846:                             ."ignored.");
                   4847:                 }
1.244     albertel 4848: 	    } else {
                   4849: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4850: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4851: 		my $store_key=$dest;
                   4852: 		$store_key=~s/^stores/resource/;
                   4853: 		$store_key=~s/_/\./g;
                   4854: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4855: 	    }
1.41      ng       4856: 	}
1.508     www      4857: 	if (! %grades) { 
                   4858:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4859:         } else {
                   4860: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4861: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4862: 					   $env{'request.course.id'},
                   4863: 					   $domain,$username);
1.508     www      4864: 	   if ($result eq 'ok') {
1.627     www      4865: # Successfully stored
1.508     www      4866: 	      $request->print('.');
1.627     www      4867: # Remove from grading queue
                   4868:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4869:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4870:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4871:                                              $domain,$username);
                   4872:               $countdone++;
                   4873:            } else {
1.508     www      4874: 	      $request->print("<p><span class=\"LC_error\">".
                   4875:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4876:                                   "$username:$domain",$result)."</span></p>");
                   4877: 	   }
                   4878: 	   $request->rflush();
                   4879:         }
1.41      ng       4880:     }
1.570     www      4881:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4882:     if (@warnings) {
                   4883:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4884:         $request->print(join(', ',@warnings));
                   4885:     }
1.41      ng       4886:     if (@skipped) {
1.571     www      4887: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4888:         $request->print(join(', ',@skipped));
1.106     albertel 4889:     }
                   4890:     if (@notallowed) {
1.571     www      4891: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4892: 	$request->print(join(', ',@notallowed));
1.41      ng       4893:     }
1.106     albertel 4894:     $request->print("<br />\n");
1.345     bowersj2 4895:     return $error_msg;
1.26      albertel 4896: }
1.44      ng       4897: #------------- end of section for handling csv file upload ---------
                   4898: #
                   4899: #-------------------------------------------------------------------
                   4900: #
1.122     ng       4901: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4902: #
                   4903: #--- Select a page/sequence and a student to grade
1.68      ng       4904: sub pickStudentPage {
1.608     www      4905:     my ($request,$symb) = @_;
1.68      ng       4906: 
1.539     riegler  4907:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.736     damieng  4908:     &js_escape(\$alertmsg);
1.597     wenzelju 4909:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4910: 
                   4911: function checkPickOne(formname) {
1.76      ng       4912:     if (radioSelection(formname.student) == null) {
1.539     riegler  4913: 	alert("$alertmsg");
1.68      ng       4914: 	return;
                   4915:     }
1.125     ng       4916:     ptr = pullDownSelection(formname.selectpage);
                   4917:     formname.page.value = formname["page"+ptr].value;
                   4918:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4919:     formname.submit();
                   4920: }
                   4921: 
                   4922: LISTJAVASCRIPT
1.118     ng       4923:     &commonJSfunctions($request);
1.608     www      4924: 
1.257     albertel 4925:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4926:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4927:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.761   ! raeburn  4928:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.68      ng       4929: 
1.398     albertel 4930:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4931: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4932: 
1.80      ng       4933:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4934:     my $map_error;
                   4935:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4936:     if ($map_error) {
                   4937:         $request->print(&navmap_errormsg());
                   4938:         return; 
                   4939:     }
1.137     albertel 4940:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4941: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4942: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4943: 
                   4944:     # Collection of hidden fields
1.70      ng       4945:     my $ctr=0;
1.68      ng       4946:     foreach (@$titles) {
1.700     bisitz   4947:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4948:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4949:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4950:         $ctr++;
1.68      ng       4951:     }
1.700     bisitz   4952:     $result.='<input type="hidden" name="page" />'."\n".
                   4953:         '<input type="hidden" name="title" />'."\n";
                   4954: 
                   4955:     $result.=&build_section_inputs();
                   4956:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4957:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4958: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4959: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4960: 
1.700     bisitz   4961:     # Show grading options
                   4962:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4963:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4964:     $ctr=0;
                   4965:     foreach (@$titles) {
                   4966: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4967: 	$select.='<option value="'.$ctr.'"'.
                   4968: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4969: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4970: 	$ctr++;
                   4971:     }
1.700     bisitz   4972:     $select.= '</select>';
1.68      ng       4973: 
1.700     bisitz   4974:     $result.=
                   4975:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4976:        .$select
                   4977:        .&Apache::lonhtmlcommon::row_closure();
                   4978: 
                   4979:     $result.=
                   4980:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4981:        .'<label><input type="radio" name="vProb" value="no"'
                   4982:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4983:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4984:            .&mt('yes').'</label>'."\n"
                   4985:        .&Apache::lonhtmlcommon::row_closure();
                   4986: 
                   4987:     $result.=
                   4988:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4989:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4990:            .&mt('none').' </label>'."\n"
                   4991:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4992:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4993:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4994:            .&mt('all submissions with details').' </label>'
                   4995:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4996:     
1.700     bisitz   4997:     $result.=
                   4998:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4999:        .'<input type="text" name="CODE" value="" />'
                   5000:        .&Apache::lonhtmlcommon::row_closure(1)
                   5001:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 5002: 
1.700     bisitz   5003:     # Show list of students to select for grading
                   5004:     $result.='<br /><input type="button" '.
1.589     bisitz   5005:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       5006: 
1.68      ng       5007:     $request->print($result);
                   5008: 
1.485     albertel 5009:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 5010: 	&Apache::loncommon::start_data_table().
                   5011: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5012: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5013: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 5014: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 5015: 	'<th>'.&nameUserString('header').'</th>'.
                   5016: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       5017:  
1.761   ! raeburn  5018:     my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
1.68      ng       5019:     my $ptr = 1;
1.294     albertel 5020:     foreach my $student (sort 
                   5021: 			 {
                   5022: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   5023: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   5024: 			     }
                   5025: 			     return $a cmp $b;
                   5026: 			 } (keys(%$fullname))) {
1.68      ng       5027: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 5028: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   5029:                                   : '</td>');
1.126     ng       5030: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 5031: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   5032: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 5033: 	$studentTable.=
                   5034: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   5035:                          : '');
1.68      ng       5036: 	$ptr++;
                   5037:     }
1.484     albertel 5038:     if ($ptr%2 == 0) {
                   5039: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   5040: 	    &Apache::loncommon::end_data_table_row();
                   5041:     }
                   5042:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       5043:     $studentTable.='<input type="button" '.
1.589     bisitz   5044:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       5045: 
                   5046:     $request->print($studentTable);
                   5047: 
                   5048:     return '';
                   5049: }
                   5050: 
                   5051: sub getSymbMap {
1.582     raeburn  5052:     my ($map_error) = @_;
1.132     bowersj2 5053:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5054:     unless (ref($navmap)) {
                   5055:         if (ref($map_error)) {
                   5056:             $$map_error = 'navmap';
                   5057:         }
                   5058:         return;
                   5059:     }
1.68      ng       5060:     my %symbx = ();
                   5061:     my @titles = ();
1.117     bowersj2 5062:     my $minder = 0;
                   5063: 
                   5064:     # Gather every sequence that has problems.
1.240     albertel 5065:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   5066: 					       1,0,1);
1.117     bowersj2 5067:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.745     raeburn  5068: 	if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
1.381     albertel 5069: 	    my $title = $minder.'.'.
                   5070: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   5071: 	    push(@titles, $title); # minder in case two titles are identical
                   5072: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 5073: 	    $minder++;
1.241     albertel 5074: 	}
1.68      ng       5075:     }
                   5076:     return \@titles,\%symbx;
                   5077: }
                   5078: 
1.72      ng       5079: #
                   5080: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       5081: sub displayPage {
1.608     www      5082:     my ($request,$symb) = @_;
1.257     albertel 5083:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5084:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5085:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5086:     my $pageTitle = $env{'form.page'};
1.103     albertel 5087:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5088:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5089:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5090: 
                   5091:     #need to make sure we have the correct data for later EXT calls, 
                   5092:     #thus invalidate the cache
                   5093:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5094:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5095:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5096:     &Apache::lonnet::clear_EXT_cache_status();
                   5097: 
1.103     albertel 5098:     if (!&canview($usec)) {
1.712     bisitz   5099:         $request->print(
                   5100:             '<span class="LC_warning">'.
                   5101:             &mt('Unable to view requested student. ([_1])',
                   5102:                     $env{'form.student'}).
                   5103:             '</span>');
                   5104:         return;
1.103     albertel 5105:     }
1.398     albertel 5106:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5107:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5108: 	'</h3>'."\n";
1.500     albertel 5109:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5110:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5111: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5112:     } else {
                   5113: 	delete($env{'form.CODE'});
                   5114:     }
1.71      ng       5115:     &sub_page_js($request);
                   5116:     $request->print($result);
                   5117: 
1.132     bowersj2 5118:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5119:     unless (ref($navmap)) {
                   5120:         $request->print(&navmap_errormsg());
                   5121:         return;
                   5122:     }
1.257     albertel 5123:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5124:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5125:     if (!$map) {
1.485     albertel 5126: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 5127: 	return; 
                   5128:     }
1.68      ng       5129:     my $iterator = $navmap->getIterator($map->map_start(),
                   5130: 					$map->map_finish());
                   5131: 
1.71      ng       5132:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5133: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5134: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5135: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5136: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5137: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5138: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      5139: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       5140: 
1.382     albertel 5141:     if (defined($env{'form.CODE'})) {
                   5142: 	$studentTable.=
                   5143: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5144:     }
1.381     albertel 5145:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5146: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5147: 
1.594     bisitz   5148:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5149:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5150:         '</span>'."\n".
1.484     albertel 5151: 	&Apache::loncommon::start_data_table().
                   5152: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   5153: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 5154: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5155: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5156: 
1.329     albertel 5157:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5158:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5159:     $iterator->next(); # skip the first BEGIN_MAP
                   5160:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5161:     while ($depth > 0) {
1.68      ng       5162:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5163:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5164: 
1.745     raeburn  5165:         if (ref($curRes) && $curRes->is_gradable()) {
1.91      albertel 5166: 	    my $parts = $curRes->parts();
1.68      ng       5167:             my $title = $curRes->compTitle();
1.71      ng       5168: 	    my $symbx = $curRes->symb();
1.746     raeburn  5169:             my $is_tool = ($symbx =~ /ext\.tool$/);
1.484     albertel 5170: 	    $studentTable.=
                   5171: 		&Apache::loncommon::start_data_table_row().
                   5172: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5173: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  5174: 		                        : '<br />('.&mt('[_1]parts',
                   5175: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5176: 		 ).
                   5177: 		 '</td>';
1.71      ng       5178: 	    $studentTable.='<td valign="top">';
1.382     albertel 5179: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.749     raeburn  5180:             if ($is_tool) {
                   5181:                 $studentTable.='&nbsp;<b>'.$title.'</b><br />';
                   5182:             } else {
1.745     raeburn  5183: 	        if ($env{'form.vProb'} eq 'yes' ) {
                   5184: 		    $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   5185: 					         undef,'both',\%form);
                   5186: 	        } else {
                   5187: 		    my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
                   5188: 		    $companswer =~ s|<form(.*?)>||g;
                   5189: 		    $companswer =~ s|</form>||g;
                   5190: #		    while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
                   5191: #		        $companswer =~ s/$1/ /ms;
                   5192: #		        $request->print('match='.$1."<br />\n");
                   5193: #		    }
                   5194: #		    $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
                   5195: 		    $studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
                   5196: 		}
1.71      ng       5197: 	    }
                   5198: 
1.257     albertel 5199: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5200: 
1.257     albertel 5201: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5202: 		if ($record{'version'} eq '') {
1.745     raeburn  5203:                     my $msg = &mt('No recorded submission for this problem.');
                   5204:                     if ($is_tool) {
                   5205:                         $msg = &mt('No recorded transactions for this external tool');
                   5206:                     }
                   5207: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.$msg.'</span><br />';
1.71      ng       5208: 		} else {
1.116     ng       5209: 		    my %responseType = ();
                   5210: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5211: 			my @responseIds =$curRes->responseIds($partid);
                   5212: 			my @responseType =$curRes->responseType($partid);
                   5213: 			my %responseIds;
                   5214: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5215: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5216: 			}
                   5217: 			$responseType{$partid} = \%responseIds;
1.116     ng       5218: 		    }
1.148     albertel 5219: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.71      ng       5220: 		}
1.257     albertel 5221: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5222: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  5223:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       5224: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5225: 									$env{'request.course.id'},
1.726     raeburn  5226: 									'','.submission',undef,
                   5227:                                                                         $usec,$identifier);
1.71      ng       5228:  
                   5229: 	    }
1.103     albertel 5230: 	    if (&canmodify($usec)) {
1.585     bisitz   5231:             $studentTable.=&gradeBox_start();
1.103     albertel 5232: 		foreach my $partid (@{$parts}) {
                   5233: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5234: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5235: 		    $question++;
                   5236: 		}
1.585     bisitz   5237:             $studentTable.=&gradeBox_end();
1.196     albertel 5238: 		$prob++;
1.71      ng       5239: 	    }
                   5240: 	    $studentTable.='</td></tr>';
1.68      ng       5241: 
1.103     albertel 5242: 	}
1.68      ng       5243:         $curRes = $iterator->next();
                   5244:     }
                   5245: 
1.589     bisitz   5246:     $studentTable.=
                   5247:         '</table>'."\n".
                   5248:         '<input type="button" value="'.&mt('Save').'" '.
                   5249:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5250:         '</form>'."\n";
1.71      ng       5251:     $request->print($studentTable);
                   5252: 
                   5253:     return '';
1.119     ng       5254: }
                   5255: 
                   5256: sub displaySubByDates {
1.148     albertel 5257:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5258:     my $isCODE=0;
1.335     albertel 5259:     my $isTask = ($symb =~/\.task$/);
1.747     raeburn  5260:     my $is_tool = ($symb =~/\.tool$/);
1.224     albertel 5261:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5262:     my $studentTable=&Apache::loncommon::start_data_table().
                   5263: 	&Apache::loncommon::start_data_table_header_row().
                   5264: 	'<th>'.&mt('Date/Time').'</th>'.
                   5265: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  5266:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.749     raeburn  5267: 	'<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
1.467     albertel 5268: 	'<th>'.&mt('Status').'</th>'.
                   5269: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5270:     my ($version);
                   5271:     my %mark;
1.148     albertel 5272:     my %orders;
1.119     ng       5273:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5274:     if (!exists($$record{'1:timestamp'})) {
1.747     raeburn  5275:         if ($is_tool) {
                   5276:             return '<br />&nbsp;<span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
                   5277:         } else {
                   5278:             return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
                   5279:         }
1.147     albertel 5280:     }
1.335     albertel 5281: 
                   5282:     my $interaction;
1.525     raeburn  5283:     my $no_increment = 1;
1.735     raeburn  5284:     my (%lastrndseed,%lasttype);
1.119     ng       5285:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5286: 	my $timestamp = 
                   5287: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5288: 	if (exists($$record{$version.':resource.0.version'})) {
                   5289: 	    $interaction = $$record{$version.':resource.0.version'};
                   5290: 	}
1.671     raeburn  5291:         if ($isTask && $env{'form.previousversion'}) {
                   5292:             next unless ($interaction == $env{'form.previousversion'});
                   5293:         }
1.335     albertel 5294: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5295: 		             : "$version:resource");
1.467     albertel 5296: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5297: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5298: 	if ($isCODE) {
                   5299: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5300: 	}
1.671     raeburn  5301:         if ($isTask) {
                   5302:             $studentTable.='<td>'.$interaction.'</td>';
                   5303:         }
1.119     ng       5304: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5305: 	my @displaySub = ();
                   5306: 	foreach my $partid (@{$parts}) {
1.640     raeburn  5307:             my ($hidden,$type);
                   5308:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5309:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5310:                 $hidden = 1;
                   5311:             }
1.749     raeburn  5312:             my @matchKey;
                   5313:             if ($isTask) {
                   5314:                 @matchKey = sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys);
                   5315:             } elsif ($is_tool) {
                   5316:                 @matchKey = sort(grep /^resource\.\Q$partid\E\.awarded$/,@versionKeys);
                   5317:             } else {
                   5318:                 @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
                   5319:             }
1.122     ng       5320: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5321: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5322: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5323: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5324: 		    $$record{$version.':'.$matchKey} ne '') {
1.749     raeburn  5325:                     if ($is_tool) {
                   5326:                         $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
1.596     raeburn  5327:                     } else {
1.749     raeburn  5328: 		        my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5329: 				                   : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   5330:                         $displaySub[0].='<span class="LC_nobreak">';
                   5331:                         $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5332:                                        .' <span class="LC_internal_info">'
                   5333:                                        .'('.&mt('Response ID: [_1]',$responseId).')'
                   5334:                                        .'</span>'
                   5335:                                        .' <b>';
                   5336:                         if ($hidden) {
                   5337:                             $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5338:                         } else {
                   5339:                             my ($trial,$rndseed,$newvariation);
                   5340:                             if ($type eq 'randomizetry') {
                   5341:                                 $trial = $$record{"$where.$partid.tries"};
                   5342:                                 $rndseed = $$record{"$where.$partid.rndseed"};
                   5343:                             }
                   5344: 		            if ($$record{"$where.$partid.tries"} eq '') {
                   5345: 			        $displaySub[0].=&mt('Trial not counted');
                   5346: 		            } else {
                   5347: 			        $displaySub[0].=&mt('Trial: [_1]',
                   5348: 					        $$record{"$where.$partid.tries"});
                   5349:                                 if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
                   5350:                                     if (($rndseed ne $lastrndseed{$partid}) &&
                   5351:                                         (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
                   5352:                                         $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5353:                                     }
1.640     raeburn  5354:                                 }
1.749     raeburn  5355:                                 $lastrndseed{$partid} = $rndseed;
                   5356:                                 $lasttype{$partid} = $type;
                   5357: 		            }
                   5358: 		            my $responseType=($isTask ? 'Task'
1.335     albertel 5359:                                               : $responseType->{$partid}->{$responseId});
1.749     raeburn  5360: 		            if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   5361: 		            if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
                   5362: 			        $orders{$partid}->{$responseId}=
                   5363: 			            &get_order($partid,$responseId,$symb,$uname,$udom,
                   5364:                                                $no_increment,$type,$trial,$rndseed);
                   5365: 		            }
                   5366: 		            $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
                   5367: 		            $displaySub[0].='&nbsp; '.
                   5368: 			        &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
                   5369:                         }
1.596     raeburn  5370:                     }
1.147     albertel 5371: 		}
                   5372: 	    }
1.335     albertel 5373: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5374: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5375: 				    $$record{"$where.$partid.checkedin"},
                   5376: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5377: 					'<br />';
1.335     albertel 5378: 	    }
                   5379: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5380: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5381: 		    lc($$record{"$where.$partid.award"}).' '.
                   5382: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5383: 		    '<br />';
1.749     raeburn  5384: 	    } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
                   5385: 		if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
                   5386: 		    $displaySub[1].=&mt('Grade passed back by external tool');
                   5387: 		}
1.147     albertel 5388: 	    }
1.335     albertel 5389: 	    if (exists $$record{"$where.$partid.regrader"}) {
1.749     raeburn  5390: 		$displaySub[2].=$$record{"$where.$partid.regrader"};
                   5391: 		unless ($is_tool) {
                   5392: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5393: 		}
1.335     albertel 5394: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5395: 		$displaySub[2].=
1.749     raeburn  5396: 		    $$record{"$version:resource.$partid.regrader"};
                   5397:                 unless ($is_tool) {
                   5398: 		    $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5399:                 }
1.147     albertel 5400: 	    }
                   5401: 	}
                   5402: 	# needed because old essay regrader has not parts info
                   5403: 	if (exists $$record{"$version:resource.regrader"}) {
                   5404: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5405: 	}
                   5406: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5407: 	if ($displaySub[2]) {
1.467     albertel 5408: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5409: 	}
1.467     albertel 5410: 	$studentTable.='&nbsp;</td>'.
                   5411: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5412:     }
1.467     albertel 5413:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5414:     return $studentTable;
1.71      ng       5415: }
                   5416: 
                   5417: sub updateGradeByPage {
1.608     www      5418:     my ($request,$symb) = @_;
1.71      ng       5419: 
1.257     albertel 5420:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5421:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5422:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5423:     my $pageTitle = $env{'form.page'};
1.103     albertel 5424:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5425:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5426:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5427:     if (!&canmodify($usec)) {
1.526     raeburn  5428: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 5429: 	return;
                   5430:     }
1.398     albertel 5431:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5432:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5433: 	'</h3>'."\n";
1.70      ng       5434: 
1.68      ng       5435:     $request->print($result);
                   5436: 
1.582     raeburn  5437: 
1.132     bowersj2 5438:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5439:     unless (ref($navmap)) {
                   5440:         $request->print(&navmap_errormsg());
                   5441:         return;
                   5442:     }
1.257     albertel 5443:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5444:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5445:     if (!$map) {
1.527     raeburn  5446: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 5447: 	return; 
                   5448:     }
1.71      ng       5449:     my $iterator = $navmap->getIterator($map->map_start(),
                   5450: 					$map->map_finish());
1.70      ng       5451: 
1.484     albertel 5452:     my $studentTable=
                   5453: 	&Apache::loncommon::start_data_table().
                   5454: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5455: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5456: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5457: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5458: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5459: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5460: 
                   5461:     $iterator->next(); # skip the first BEGIN_MAP
                   5462:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  5463:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5464:     while ($depth > 0) {
1.71      ng       5465:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5466:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5467: 
1.385     albertel 5468:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5469: 	    my $parts = $curRes->parts();
1.71      ng       5470:             my $title = $curRes->compTitle();
                   5471: 	    my $symbx = $curRes->symb();
1.484     albertel 5472: 	    $studentTable.=
                   5473: 		&Apache::loncommon::start_data_table_row().
                   5474: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5475: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  5476:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5477: 		.')').'</td>';
1.71      ng       5478: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5479: 
                   5480: 	    my %newrecord=();
                   5481: 	    my @displayPts=();
1.269     raeburn  5482:             my %aggregate = ();
                   5483:             my $aggregateflag = 0;
1.726     raeburn  5484:             if ($env{'form.HIDE'.$prob}) {
                   5485:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  5486:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  5487:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  5488:                 $hideflag += $numchgs;
                   5489:             }
1.71      ng       5490: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5491: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5492: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5493: 
1.257     albertel 5494: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5495: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5496: 		my $partial = $newpts/$wgt;
                   5497: 		my $score;
                   5498: 		if ($partial > 0) {
                   5499: 		    $score = 'correct_by_override';
1.125     ng       5500: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5501: 		    $score = 'incorrect_by_override';
                   5502: 		}
1.257     albertel 5503: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5504: 		if ($dropMenu eq 'excused') {
1.71      ng       5505: 		    $partial = '';
                   5506: 		    $score = 'excused';
1.125     ng       5507: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5508: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5509: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5510: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5511: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5512: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5513: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5514: 		    $changeflag++;
                   5515: 		    $newpts = '';
1.269     raeburn  5516:                     
                   5517:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5518:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5519:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5520:                     if ($aggtries > 0) {
                   5521:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5522:                         $aggregateflag = 1;
                   5523:                     }
1.71      ng       5524: 		}
1.324     albertel 5525: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5526: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5527: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5528: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5529: 		    '&nbsp;<br />';
1.526     raeburn  5530: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5531: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5532: 		    '&nbsp;<br />';
1.71      ng       5533: 		$question++;
1.380     albertel 5534: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5535: 
1.71      ng       5536: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5537: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5538: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5539: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5540: 
                   5541: 		$changeflag++;
                   5542: 	    }
                   5543: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5544: 		my %record = 
                   5545: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5546: 					     $udom,$uname);
                   5547: 
                   5548: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5549: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5550: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5551: 		    $newrecord{'resource.CODE'} = '';
                   5552: 		}
1.257     albertel 5553: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5554: 					$udom,$uname);
1.382     albertel 5555: 		%record = &Apache::lonnet::restore($symbx,
                   5556: 						   $env{'request.course.id'},
                   5557: 						   $udom,$uname);
1.380     albertel 5558: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5559: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5560: 	    }
1.380     albertel 5561: 	    
1.269     raeburn  5562:             if ($aggregateflag) {
                   5563:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5564:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5565:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5566:             }
1.125     ng       5567: 
1.71      ng       5568: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5569: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5570: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5571: 
1.196     albertel 5572: 	    $prob++;
1.68      ng       5573: 	}
1.71      ng       5574:         $curRes = $iterator->next();
1.68      ng       5575:     }
1.98      albertel 5576: 
1.484     albertel 5577:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5578:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5579: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5580: 		  $changeflag).'<br />');
                   5581:     my $hidemsg=($hideflag == 0 ? '' :
                   5582:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5583:                      $hideflag).'<br />');
                   5584:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5585: 
1.70      ng       5586:     return '';
                   5587: }
                   5588: 
1.72      ng       5589: #-------- end of section for handling grading by page/sequence ---------
                   5590: #
                   5591: #-------------------------------------------------------------------
                   5592: 
1.581     www      5593: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5594: #
                   5595: #------ start of section for handling grading by page/sequence ---------
                   5596: 
1.423     albertel 5597: =pod
                   5598: 
                   5599: =head1 Bubble sheet grading routines
                   5600: 
1.424     albertel 5601:   For this documentation:
                   5602: 
                   5603:    'scanline' refers to the full line of characters
                   5604:    from the file that we are parsing that represents one entire sheet
                   5605: 
                   5606:    'bubble line' refers to the data
1.659     raeburn  5607:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5608: 
                   5609: 
1.659     raeburn  5610: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5611: into a course. When a user wants to grade, they select a
1.659     raeburn  5612: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5613: one of the predefined configurations for what each scanline looks
                   5614: like.
                   5615: 
                   5616: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5617: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5618: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5619: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5620: invalid student/employee ID
1.424     albertel 5621: 
                   5622: If the CODE option is used that determines the randomization of the
1.556     weissno  5623: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5624: username:domain.
                   5625: 
                   5626: During the validation phase the instructor can choose to skip scanlines. 
                   5627: 
1.659     raeburn  5628: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5629: 
                   5630:   scantron_original_filename (unmodified original file)
                   5631:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5632:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5633: 
                   5634: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5635: correction information that isn't representable in the bubblesheet
1.424     albertel 5636: file (see &scantron_getfile() for more information)
                   5637: 
                   5638: After all scanlines are either valid, marked as valid or skipped, then
                   5639: foreach line foreach problem in the picked sequence, an ssi request is
                   5640: made that simulates a user submitting their selected letter(s) against
                   5641: the homework problem.
1.423     albertel 5642: 
                   5643: =over 4
                   5644: 
                   5645: 
                   5646: 
                   5647: =item defaultFormData
                   5648: 
                   5649:   Returns html hidden inputs used to hold context/default values.
                   5650: 
                   5651:  Arguments:
                   5652:   $symb - $symb of the current resource 
                   5653: 
                   5654: =cut
1.422     foxr     5655: 
1.81      albertel 5656: sub defaultFormData {
1.324     albertel 5657:     my ($symb)=@_;
1.613     www      5658:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5659: }
                   5660: 
1.447     foxr     5661: 
1.423     albertel 5662: =pod 
                   5663: 
                   5664: =item getSequenceDropDown
                   5665: 
                   5666:    Return html dropdown of possible sequences to grade
                   5667:  
                   5668:  Arguments:
1.582     raeburn  5669:    $symb - $symb of the current resource
                   5670:    $map_error - ref to scalar which will container error if
                   5671:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5672: 
                   5673: =cut
1.422     foxr     5674: 
1.75      albertel 5675: sub getSequenceDropDown {
1.582     raeburn  5676:     my ($symb,$map_error)=@_;
1.75      albertel 5677:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5678:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5679:     if (ref($map_error)) {
                   5680:         return if ($$map_error);
                   5681:     }
1.137     albertel 5682:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5683:     my $ctr=0;
                   5684:     foreach (@$titles) {
                   5685: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5686: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5687: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5688: 	    '>'.$showtitle.'</option>'."\n";
                   5689: 	$ctr++;
                   5690:     }
                   5691:     $result.= '</select>';
                   5692:     return $result;
                   5693: }
                   5694: 
1.495     albertel 5695: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5696:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5697: 
                   5698: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5699: 
1.509     raeburn  5700: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5701:                                    # matchresponse or rankresponse, where 
                   5702:                                    # an individual response can have multiple 
                   5703:                                    # lines
1.503     raeburn  5704: 
                   5705: my %responsetype_per_response;     # responsetype for each response
                   5706: 
1.691     raeburn  5707: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5708:                                    # numbered response. Needed when randomorder
                   5709:                                    # or randompick are in use. Key is ID, value 
                   5710:                                    # is response number.
                   5711: 
1.495     albertel 5712: # Save and restore the bubble lines array to the form env.
                   5713: 
                   5714: 
                   5715: sub save_bubble_lines {
                   5716:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5717: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5718: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5719: 	    $first_bubble_line{$line};
1.503     raeburn  5720:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5721:             $subdivided_bubble_lines{$line};
                   5722:         $env{"form.scantron.responsetype.$line"} =
                   5723:             $responsetype_per_response{$line};
1.495     albertel 5724:     }
1.691     raeburn  5725:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5726:         my $line = $masterseq_id_responsenum{$resid};
                   5727:         $env{"form.scantron.residpart.$line"} = $resid;
                   5728:     }
1.495     albertel 5729: }
                   5730: 
                   5731: 
                   5732: sub restore_bubble_lines {
                   5733:     my $line = 0;
                   5734:     %bubble_lines_per_response = ();
1.691     raeburn  5735:     %masterseq_id_responsenum = ();
1.495     albertel 5736:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5737: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5738: 	$bubble_lines_per_response{$line} = $value;
                   5739: 	$first_bubble_line{$line}  =
                   5740: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5741:         $subdivided_bubble_lines{$line} =
                   5742:             $env{"form.scantron.sub_bubblelines.$line"};
                   5743:         $responsetype_per_response{$line} =
                   5744:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5745:         my $id = $env{"form.scantron.residpart.$line"};
                   5746:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5747: 	$line++;
                   5748:     }
                   5749: }
                   5750: 
1.423     albertel 5751: =pod 
                   5752: 
                   5753: =item scantron_filenames
                   5754: 
                   5755:    Returns a list of the scantron files in the current course 
                   5756: 
                   5757: =cut
1.422     foxr     5758: 
1.202     albertel 5759: sub scantron_filenames {
1.257     albertel 5760:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5761:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5762:     my $getpropath = 1;
1.662     raeburn  5763:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5764:                                                         $cname,$getpropath);
1.202     albertel 5765:     my @possiblenames;
1.662     raeburn  5766:     if (ref($dirlist) eq 'ARRAY') {
                   5767:         foreach my $filename (sort(@{$dirlist})) {
                   5768: 	    ($filename)=split(/&/,$filename);
                   5769: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5770: 	    $filename=~s/^scantron_orig_//;
                   5771: 	    push(@possiblenames,$filename);
                   5772:         }
1.202     albertel 5773:     }
                   5774:     return @possiblenames;
                   5775: }
                   5776: 
1.423     albertel 5777: =pod 
                   5778: 
                   5779: =item scantron_uploads
                   5780: 
                   5781:    Returns  html drop-down list of scantron files in current course.
                   5782: 
                   5783:  Arguments:
                   5784:    $file2grade - filename to set as selected in the dropdown
                   5785: 
                   5786: =cut
1.422     foxr     5787: 
1.202     albertel 5788: sub scantron_uploads {
1.209     ng       5789:     my ($file2grade) = @_;
1.202     albertel 5790:     my $result=	'<select name="scantron_selectfile">';
                   5791:     $result.="<option></option>";
                   5792:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5793: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5794:     }
                   5795:     $result.="</select>";
                   5796:     return $result;
                   5797: }
                   5798: 
1.423     albertel 5799: =pod 
                   5800: 
                   5801: =item scantron_scantab
                   5802: 
                   5803:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5804:   file.
                   5805: 
                   5806: =cut
1.422     foxr     5807: 
1.82      albertel 5808: sub scantron_scantab {
                   5809:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5810:     $result.='<option></option>'."\n";
1.754     raeburn  5811:     my @lines = &Apache::lonnet::get_scantronformat_file();
1.518     raeburn  5812:     if (@lines > 0) {
                   5813:         foreach my $line (@lines) {
                   5814:             next if (($line =~ /^\#/) || ($line eq ''));
                   5815: 	    my ($name,$descrip)=split(/:/,$line);
                   5816: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5817:         }
1.82      albertel 5818:     }
                   5819:     $result.='</select>'."\n";
1.518     raeburn  5820:     return $result;
                   5821: }
                   5822: 
1.423     albertel 5823: =pod 
                   5824: 
                   5825: =item scantron_CODElist
                   5826: 
                   5827:   Returns html drop down of the saved CODE lists from current course,
                   5828:   generated from earlier printings.
                   5829: 
                   5830: =cut
1.422     foxr     5831: 
1.186     albertel 5832: sub scantron_CODElist {
1.257     albertel 5833:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5834:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5835:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5836:     my $namechoice='<option></option>';
1.225     albertel 5837:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5838: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5839: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5840: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5841:     }
                   5842:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5843:     return $namechoice;
                   5844: }
                   5845: 
1.423     albertel 5846: =pod 
                   5847: 
                   5848: =item scantron_CODEunique
                   5849: 
                   5850:   Returns the html for "Each CODE to be used once" radio.
                   5851: 
                   5852: =cut
1.422     foxr     5853: 
1.186     albertel 5854: sub scantron_CODEunique {
1.532     bisitz   5855:     my $result='<span class="LC_nobreak">
1.272     albertel 5856:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5857:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5858:                 </span>
1.532     bisitz   5859:                 <span class="LC_nobreak">
1.272     albertel 5860:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5861:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5862:                 </span>';
1.186     albertel 5863:     return $result;
                   5864: }
1.423     albertel 5865: 
                   5866: =pod 
                   5867: 
                   5868: =item scantron_selectphase
                   5869: 
1.659     raeburn  5870:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5871:   Allows for - starting a grading run.
1.424     albertel 5872:              - downloading existing scan data (original, corrected
1.423     albertel 5873:                                                 or skipped info)
                   5874: 
                   5875:              - uploading new scan data
                   5876: 
                   5877:  Arguments:
                   5878:   $r          - The Apache request object
                   5879:   $file2grade - name of the file that contain the scanned data to score
                   5880: 
                   5881: =cut
1.186     albertel 5882: 
1.75      albertel 5883: sub scantron_selectphase {
1.608     www      5884:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5885:     if (!$symb) {return '';}
1.582     raeburn  5886:     my $map_error;
                   5887:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5888:     if ($map_error) {
                   5889:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5890:         return;
                   5891:     }
1.324     albertel 5892:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5893:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5894:     my $format_selector=&scantron_scantab();
1.186     albertel 5895:     my $CODE_selector=&scantron_CODElist();
                   5896:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5897:     my $result;
1.422     foxr     5898: 
1.513     foxr     5899:     $ssi_error = 0;
                   5900: 
1.606     wenzelju 5901:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5902:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5903: 
                   5904: 	# Chunk of form to prompt for a scantron file upload.
                   5905: 
                   5906:         $r->print('
1.754     raeburn  5907:     <br />');
1.606     wenzelju 5908:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5909:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.736     damieng  5910:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5911:     &js_escape(\$alertmsg);
1.754     raeburn  5912:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
1.606     wenzelju 5913:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5914:     function checkUpload(formname) {
                   5915: 	if (formname.upfile.value == "") {
1.736     damieng  5916: 	    alert("'.$alertmsg.'");
1.606     wenzelju 5917: 	    return false;
                   5918: 	}
                   5919: 	formname.submit();
1.756     raeburn  5920:     }'."\n".$formatjs));
1.606     wenzelju 5921:     $r->print('
                   5922:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5923:                 '.$default_form_data.'
                   5924:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   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: 
                   6006: 
                   6007:     # Chunk of the form that prompts to view a scoring office file,
                   6008:     # corrected file, skipped records in a file.
                   6009: 
1.489     albertel 6010:     $r->print('
                   6011:    <br />
                   6012:    <form action="/adm/grades" name="scantron_download">
                   6013:      '.$default_form_data.'
                   6014:      <input type="hidden" name="command" value="scantron_download" />
                   6015:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   6016:        '.&Apache::loncommon::start_data_table_header_row().'
                   6017:               <th>
1.492     albertel 6018:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 6019:               </th>
                   6020:        '.&Apache::loncommon::end_data_table_header_row().'
                   6021:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 6022:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 6023:                 <br />
1.492     albertel 6024:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 6025:        '.&Apache::loncommon::end_data_table_row().'
                   6026:      '.&Apache::loncommon::end_data_table().'
                   6027:    </form>
                   6028:    <br />
                   6029: ');
1.162     albertel 6030: 
1.457     banghart 6031:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  6032: 
1.694     bisitz   6033:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  6034:              $default_form_data."\n".
                   6035:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   6036:              &Apache::loncommon::start_data_table_header_row()."\n".
                   6037:              '<th colspan="2">
1.572     www      6038:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  6039:              '</th>'."\n".
                   6040:               &Apache::loncommon::end_data_table_header_row()."\n".
                   6041:               &Apache::loncommon::start_data_table_row()."\n".
                   6042:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   6043:               '<td> '.$sequence_selector.' </td>'.
                   6044:               &Apache::loncommon::end_data_table_row()."\n".
                   6045:               &Apache::loncommon::start_data_table_row()."\n".
                   6046:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   6047:               '<td> '.$file_selector.' </td>'."\n".
                   6048:               &Apache::loncommon::end_data_table_row()."\n".
                   6049:               &Apache::loncommon::start_data_table_row()."\n".
                   6050:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   6051:               '<td> '.$format_selector.' </td>'."\n".
                   6052:               &Apache::loncommon::end_data_table_row()."\n".
                   6053:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6054:               '<td> '.&mt('Options').' </td>'."\n".
                   6055:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6056:               &Apache::loncommon::end_data_table_row()."\n".
                   6057:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6058:               '<td colspan="2">'."\n".
                   6059:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6060:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6061:               '</td>'."\n".
                   6062:               &Apache::loncommon::end_data_table_row()."\n".
                   6063:               &Apache::loncommon::end_data_table()."\n".
                   6064:               '</form><br />');
                   6065:     return;
1.75      albertel 6066: }
                   6067: 
1.423     albertel 6068: =pod 
                   6069: 
                   6070: =item username_to_idmap
                   6071: 
1.556     weissno  6072:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  6073:     student username:domain. If a single ID occurs for more than one student,
                   6074:     the status of the student is checked, and if Active, the value in the hash
                   6075:     will be set to the Active student.
1.423     albertel 6076: 
                   6077:   Arguments:
                   6078: 
                   6079:     $classlist - reference to the class list hash. This is a hash
                   6080:                  keyed by student name:domain  whose elements are references
1.424     albertel 6081:                  to arrays containing various chunks of information
1.423     albertel 6082:                  about the student. (See loncoursedata for more info).
                   6083: 
                   6084:   Returns
                   6085:     %idmap - the constructed hash
                   6086: 
                   6087: =cut
                   6088: 
1.82      albertel 6089: sub username_to_idmap {
                   6090:     my ($classlist)= @_;
                   6091:     my %idmap;
                   6092:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  6093:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6094:         unless ($id eq '') {
                   6095:             if (!exists($idmap{$id})) {
                   6096:                 $idmap{$id} = $student;
                   6097:             } else {
                   6098:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6099:                 if ($status eq 'Active') {
                   6100:                     $idmap{$id} = $student;
                   6101:                 }
                   6102:             }
                   6103:         }
1.82      albertel 6104:     }
                   6105:     return %idmap;
                   6106: }
1.423     albertel 6107: 
                   6108: =pod
                   6109: 
1.424     albertel 6110: =item scantron_fixup_scanline
1.423     albertel 6111: 
                   6112:    Process a requested correction to a scanline.
                   6113: 
                   6114:   Arguments:
1.754     raeburn  6115:     $scantron_config   - hash from &Apache::lonnet::get_scantron_config()
1.423     albertel 6116:     $scan_data         - hash of correction information 
                   6117:                           (see &scantron_getfile())
                   6118:     $line              - existing scanline
                   6119:     $whichline         - line number of the passed in scanline
                   6120:     $field             - type of change to process 
                   6121:                          (either 
1.573     bisitz   6122:                           'ID'     -> correct the student/employee ID
1.423     albertel 6123:                           'CODE'   -> correct the CODE
                   6124:                           'answer' -> fixup the submitted answers)
                   6125:     
                   6126:    $args               - hash of additional info,
                   6127:                           - 'ID' 
                   6128:                                'newid' -> studentID to use in replacement
1.424     albertel 6129:                                           of existing one
1.423     albertel 6130:                           - 'CODE' 
                   6131:                                'CODE_ignore_dup' - set to true if duplicates
                   6132:                                                    should be ignored.
                   6133: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6134:                                         if the existing unfound code should
1.423     albertel 6135:                                         be used as is
                   6136:                           - 'answer'
                   6137:                                'response' - new answer or 'none' if blank
                   6138:                                'question' - the bubble line to change
1.503     raeburn  6139:                                'questionnum' - the question identifier,
                   6140:                                                may include subquestion. 
1.423     albertel 6141: 
                   6142:   Returns:
                   6143:     $line - the modified scanline
                   6144: 
                   6145:   Side effects: 
                   6146:     $scan_data - may be updated
                   6147: 
                   6148: =cut
                   6149: 
1.82      albertel 6150: 
1.157     albertel 6151: sub scantron_fixup_scanline {
                   6152:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6153:     if ($field eq 'ID') {
                   6154: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6155: 	    return ($line,1,'New value too large');
1.157     albertel 6156: 	}
                   6157: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6158: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6159: 				     $args->{'newid'});
                   6160: 	}
                   6161: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6162: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6163: 	if ($args->{'newid'}=~/^\s*$/) {
                   6164: 	    &scan_data($scan_data,"$whichline.user",
                   6165: 		       $args->{'username'}.':'.$args->{'domain'});
                   6166: 	}
1.186     albertel 6167:     } elsif ($field eq 'CODE') {
1.192     albertel 6168: 	if ($args->{'CODE_ignore_dup'}) {
                   6169: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6170: 	}
                   6171: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6172: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6173: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6174: 		return ($line,1,'New CODE value too large');
                   6175: 	    }
                   6176: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6177: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6178: 	    }
                   6179: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6180: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6181: 	}
1.157     albertel 6182:     } elsif ($field eq 'answer') {
1.497     foxr     6183: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6184: 	my $off=$scantron_config->{'Qoff'};
                   6185: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6186: 	my $answer=${off}x$length;
                   6187: 	if ($args->{'response'} eq 'none') {
                   6188: 	    &scan_data($scan_data,
1.503     raeburn  6189: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6190: 	} else {
                   6191: 	    if ($on eq 'letter') {
                   6192: 		my @alphabet=('A'..'Z');
                   6193: 		$answer=$alphabet[$args->{'response'}];
                   6194: 	    } elsif ($on eq 'number') {
                   6195: 		$answer=$args->{'response'}+1;
                   6196: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6197: 	    } else {
1.497     foxr     6198: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6199: 	    }
1.497     foxr     6200: 	    &scan_data($scan_data,
1.503     raeburn  6201: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6202: 	}
1.497     foxr     6203: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6204: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6205:     }
                   6206:     return $line;
                   6207: }
1.423     albertel 6208: 
                   6209: =pod
                   6210: 
                   6211: =item scan_data
                   6212: 
                   6213:     Edit or look up  an item in the scan_data hash.
                   6214: 
                   6215:   Arguments:
                   6216:     $scan_data  - The hash (see scantron_getfile)
                   6217:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6218:                   scantronfilename_key).
1.423     albertel 6219:     $data        - New value of the hash entry.
                   6220:     $delete      - If true, the entry is removed from the hash.
                   6221: 
                   6222:   Returns:
                   6223:     The new value of the hash table field (undefined if deleted).
                   6224: 
                   6225: =cut
                   6226: 
                   6227: 
1.157     albertel 6228: sub scan_data {
                   6229:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6230:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6231:     if (defined($value)) {
                   6232: 	$scan_data->{$filename.'_'.$key} = $value;
                   6233:     }
                   6234:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6235:     return $scan_data->{$filename.'_'.$key};
                   6236: }
1.423     albertel 6237: 
1.495     albertel 6238: # ----- These first few routines are general use routines.----
                   6239: 
                   6240: # Return the number of occurences of a pattern in a string.
                   6241: 
                   6242: sub occurence_count {
                   6243:     my ($string, $pattern) = @_;
                   6244: 
                   6245:     my @matches = ($string =~ /$pattern/g);
                   6246: 
                   6247:     return scalar(@matches);
                   6248: }
                   6249: 
                   6250: 
                   6251: # Take a string known to have digits and convert all the
                   6252: # digits into letters in the range J,A..I.
                   6253: 
                   6254: sub digits_to_letters {
                   6255:     my ($input) = @_;
                   6256: 
                   6257:     my @alphabet = ('J', 'A'..'I');
                   6258: 
                   6259:     my @input    = split(//, $input);
                   6260:     my $output ='';
                   6261:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6262: 	if ($input[$i] =~ /\d/) {
                   6263: 	    $output .= $alphabet[$input[$i]];
                   6264: 	} else {
                   6265: 	    $output .= $input[$i];
                   6266: 	}
                   6267:     }
                   6268:     return $output;
                   6269: }
                   6270: 
1.423     albertel 6271: =pod 
                   6272: 
                   6273: =item scantron_parse_scanline
                   6274: 
1.711     bisitz   6275:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 6276: 
                   6277:  Arguments:
1.711     bisitz   6278:     line             - The text of the bubblesheet file line to process
1.423     albertel 6279:     whichline        - Line number
1.711     bisitz   6280:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 6281:     scan_data        - Hash of extra information about the scanline
                   6282:                        (see scantron_getfile for more information)
                   6283:     just_header      - True if should not process question answers but only
                   6284:                        the stuff to the left of the answers.
1.691     raeburn  6285:     randomorder      - True if randomorder in use
                   6286:     randompick       - True if randompick in use
                   6287:     sequence         - Exam folder URL
                   6288:     master_seq       - Ref to array containing symbs in exam folder
                   6289:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6290:                        (corresponding values are resource objects)
                   6291:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6292:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6293:                        are refs to an array of resource objects, ordered
                   6294:                        according to order used for CODE, when randomorder
                   6295:                        and or randompick are in use.
                   6296:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6297:                        for current line to question number used for same question
                   6298:                         in "Master Sequence" (as seen by Course Coordinator).
                   6299:     startline        - Ref to hash where key is question number (0 is first)
                   6300:                        and value is number of first bubble line for current 
                   6301:                        student or code-based randompick and/or randomorder.
                   6302:     totalref         - Ref of scalar used to score total number of bubble
                   6303:                        lines needed for responses in a scan line (used when
                   6304:                        randompick in use. 
                   6305:     
1.423     albertel 6306:  Returns:
                   6307:    Hash containing the result of parsing the scanline
                   6308: 
                   6309:    Keys are all proceeded by the string 'scantron.'
                   6310: 
                   6311:        CODE    - the CODE in use for this scanline
                   6312:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6313:                  by the operator
                   6314:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6315:                             CODEs were selected, but the usage has been
                   6316:                             forced by the operator
1.556     weissno  6317:        ID  - student/employee ID
1.423     albertel 6318:        PaperID - if used, the ID number printed on the sheet when the 
                   6319:                  paper was scanned
                   6320:        FirstName - first name from the sheet
                   6321:        LastName  - last name from the sheet
                   6322: 
                   6323:      if just_header was not true these key may also exist
                   6324: 
1.447     foxr     6325:        missingerror - a list of bubble ranges that are considered to be answers
                   6326:                       to a single question that don't have any bubbles filled in.
                   6327:                       Of the form questionnumber:firstbubblenumber:count.
                   6328:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6329:                       to a single question that have more than one bubble filled in.
                   6330:                       Of the form questionnumber::firstbubblenumber:count
                   6331:    
                   6332:                 In the above, count is the number of bubble responses in the
                   6333:                 input line needed to represent the possible answers to the question.
                   6334:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6335:                 per line would have count = 2.
                   6336: 
1.423     albertel 6337:        maxquest     - the number of the last bubble line that was parsed
                   6338: 
                   6339:        (<number> starts at 1)
                   6340:        <number>.answer - zero or more letters representing the selected
                   6341:                          letters from the scanline for the bubble line 
                   6342:                          <number>.
                   6343:                          if blank there was either no bubble or there where
                   6344:                          multiple bubbles, (consult the keys missingerror and
                   6345:                          doubleerror if this is an error condition)
                   6346: 
                   6347: =cut
                   6348: 
1.82      albertel 6349: sub scantron_parse_scanline {
1.691     raeburn  6350:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6351:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6352:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6353: 
1.82      albertel 6354:     my %record;
1.691     raeburn  6355:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6356:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6357: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6358: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6359: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6360: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6361: 	    $record{'scantron.CODE'}=substr($data,
                   6362: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6363: 					    $$scantron_config{'CODElength'});
1.191     albertel 6364: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6365: 		$record{'scantron.useCODE'}=1;
                   6366: 	    }
1.192     albertel 6367: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6368: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6369: 	    }
1.82      albertel 6370: 	} else {
                   6371: 	    #FIXME interpret first N questions
                   6372: 	}
                   6373:     }
1.83      albertel 6374:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6375: 				  $$scantron_config{'IDlength'});
1.157     albertel 6376:     $record{'scantron.PaperID'}=
                   6377: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6378: 	       $$scantron_config{'PaperIDlength'});
                   6379:     $record{'scantron.FirstName'}=
                   6380: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6381: 	       $$scantron_config{'FirstNamelength'});
                   6382:     $record{'scantron.LastName'}=
                   6383: 	substr($data,$$scantron_config{'LastName'}-1,
                   6384: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6385:     if ($just_header) { return \%record; }
1.194     albertel 6386: 
1.82      albertel 6387:     my @alphabet=('A'..'Z');
                   6388:     my $questnum=0;
1.447     foxr     6389:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6390: 
1.691     raeburn  6391:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6392:     if ($randompick || $randomorder) {
                   6393:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6394:                                          $master_seq,$symb_to_resource,
                   6395:                                          $partids_by_symb,$orderedforcode,
                   6396:                                          $respnumlookup,$startline);
                   6397:         if ($total) {
                   6398:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6399:         }
                   6400:         if (ref($totalref)) {
                   6401:             $$totalref = $total;
                   6402:         }
                   6403:     }
                   6404:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6405:     chomp($questions);		# Get rid of any trailing \n.
                   6406:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6407:     while (length($questions)) {
1.691     raeburn  6408:         my $answers_needed;
                   6409:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6410:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6411:         } else {
                   6412: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6413:         }
1.503     raeburn  6414:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6415:                              || 1;
                   6416:         $questnum++;
                   6417:         my $quest_id = $questnum;
                   6418:         my $currentquest = substr($questions,0,$answer_length);
                   6419:         $questions       = substr($questions,$answer_length);
                   6420:         if (length($currentquest) < $answer_length) { next; }
                   6421: 
1.691     raeburn  6422:         my $subdivided;
                   6423:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6424:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6425:         } else {
                   6426:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6427:         }
                   6428:         if ($subdivided =~ /,/) {
1.503     raeburn  6429:             my $subquestnum = 1;
                   6430:             my $subquestions = $currentquest;
1.691     raeburn  6431:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6432:             foreach my $subans (@subanswers_needed) {
                   6433:                 my $subans_length =
                   6434:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6435:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6436:                 $subquestions   = substr($subquestions,$subans_length);
                   6437:                 $quest_id = "$questnum.$subquestnum";
                   6438:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6439:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6440:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6441:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6442:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6443:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6444:                 } else {
                   6445:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6446:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6447:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6448:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6449:                 }
                   6450:                 $subquestnum ++;
                   6451:             }
                   6452:         } else {
                   6453:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6454:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6455:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6456:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6457:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6458:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6459:             } else {
                   6460:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6461:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6462:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6463:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6464:             }
                   6465:         }
                   6466:     }
                   6467:     $record{'scantron.maxquest'}=$questnum;
                   6468:     return \%record;
                   6469: }
1.447     foxr     6470: 
1.691     raeburn  6471: sub get_master_seq {
                   6472:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6473:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6474:                    (ref($symb_to_resource) eq 'HASH'));
                   6475:     my $resource_error;
                   6476:     foreach my $resource (@{$resources}) {
                   6477:         my $ressymb;
                   6478:         if (ref($resource)) {
                   6479:             $ressymb = $resource->symb();
                   6480:             push(@{$master_seq},$ressymb);
                   6481:             $symb_to_resource->{$ressymb} = $resource;
                   6482:         } else {
                   6483:             $resource_error = 1;
                   6484:             last;
                   6485:         }
                   6486:     }
                   6487:     return $resource_error;
                   6488: }
                   6489: 
                   6490: sub get_respnum_lookups {
                   6491:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6492:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6493:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6494:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6495:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6496:                    (ref($startline) eq 'HASH'));
                   6497:     my ($user,$scancode);
                   6498:     if ((exists($record->{'scantron.CODE'})) &&
                   6499:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6500:         $scancode = $record->{'scantron.CODE'};
                   6501:     } else {
                   6502:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6503:     }
                   6504:     my @mapresources =
                   6505:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6506:                      $orderedforcode);
                   6507:     my $total = 0;
                   6508:     my $count = 0;
                   6509:     foreach my $resource (@mapresources) {
                   6510:         my $id = $resource->id();
                   6511:         my $symb = $resource->symb();
                   6512:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6513:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6514:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6515:                 if ($respnum ne '') {
                   6516:                     $respnumlookup->{$count} = $respnum;
                   6517:                     $startline->{$count} = $total;
                   6518:                     $total += $bubble_lines_per_response{$respnum};
                   6519:                     $count ++;
                   6520:                 }
                   6521:             }
                   6522:         }
                   6523:     }
                   6524:     return $total;
                   6525: }
                   6526: 
1.503     raeburn  6527: sub scantron_validator_lettnum {
                   6528:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6529:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6530:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6531: 
                   6532:     # Qon 'letter' implies for each slot in currquest we have:
                   6533:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6534:     #    about anything else (esp. a value of Qoff) for missing
                   6535:     #    bubbles.
                   6536:     #
                   6537:     # Qon 'number' implies each slot gives a digit that indexes the
                   6538:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6539:     #    and * or ? for double bubbles on a single line.
                   6540:     #
1.447     foxr     6541: 
1.503     raeburn  6542:     my $matchon;
                   6543:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6544:         $matchon = '[A-Z]';
                   6545:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6546:         $matchon = '\d';
                   6547:     }
                   6548:     my $occurrences = 0;
1.691     raeburn  6549:     my $responsenum = $questnum-1;
                   6550:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6551:        $responsenum = $respnumlookup->{$questnum-1} 
                   6552:     }
                   6553:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6554:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6555:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6556:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6557:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6558:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6559:         my @singlelines = split('',$currquest);
                   6560:         foreach my $entry (@singlelines) {
                   6561:             $occurrences = &occurence_count($entry,$matchon);
                   6562:             if ($occurrences > 1) {
                   6563:                 last;
                   6564:             }
1.691     raeburn  6565:         }
1.503     raeburn  6566:     } else {
                   6567:         $occurrences = &occurence_count($currquest,$matchon); 
                   6568:     }
                   6569:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6570:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6571:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6572:             my $bubble = substr($currquest,$ans,1);
                   6573:             if ($bubble =~ /$matchon/ ) {
                   6574:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6575:                     if ($bubble == 0) {
                   6576:                         $bubble = 10; 
                   6577:                     }
                   6578:                     $record->{"scantron.$ansnum.answer"} = 
                   6579:                         $alphabet->[$bubble-1];
                   6580:                 } else {
                   6581:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6582:                 }
                   6583:             } else {
                   6584:                 $record->{"scantron.$ansnum.answer"}='';
                   6585:             }
                   6586:             $ansnum++;
                   6587:         }
                   6588:     } elsif (!defined($currquest)
                   6589:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6590:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6591:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6592:             $record->{"scantron.$ansnum.answer"}='';
                   6593:             $ansnum++;
                   6594:         }
                   6595:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6596:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6597:         }
                   6598:     } else {
                   6599:         if ($$scantron_config{'Qon'} eq 'number') {
                   6600:             $currquest = &digits_to_letters($currquest);            
                   6601:         }
                   6602:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6603:             my $bubble = substr($currquest,$ans,1);
                   6604:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6605:             $ansnum++;
                   6606:         }
                   6607:     }
                   6608:     return $ansnum;
                   6609: }
1.447     foxr     6610: 
1.503     raeburn  6611: sub scantron_validator_positional {
                   6612:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6613:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6614:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6615: 
1.503     raeburn  6616:     # Otherwise there's a positional notation;
                   6617:     # each bubble line requires Qlength items, and there are filled in
                   6618:     # bubbles for each case where there 'Qon' characters.
                   6619:     #
1.447     foxr     6620: 
1.503     raeburn  6621:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6622: 
1.503     raeburn  6623:     # If the split only gives us one element.. the full length of the
                   6624:     # answer string, no bubbles are filled in:
1.447     foxr     6625: 
1.507     raeburn  6626:     if ($answers_needed eq '') {
                   6627:         return;
                   6628:     }
                   6629: 
1.503     raeburn  6630:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6631:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6632:             $record->{"scantron.$ansnum.answer"}='';
                   6633:             $ansnum++;
                   6634:         }
                   6635:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6636:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6637:         }
                   6638:     } elsif (scalar(@array) == 2) {
                   6639:         my $location = length($array[0]);
                   6640:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6641:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6642:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6643:             if ($ans eq $line_num) {
                   6644:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6645:             } else {
                   6646:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6647:             }
                   6648:             $ansnum++;
                   6649:          }
                   6650:     } else {
                   6651:         #  If there's more than one instance of a bubble character
                   6652:         #  That's a double bubble; with positional notation we can
                   6653:         #  record all the bubbles filled in as well as the
                   6654:         #  fact this response consists of multiple bubbles.
                   6655:         #
1.691     raeburn  6656:         my $responsenum = $questnum-1;
                   6657:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6658:             $responsenum = $respnumlookup->{$questnum-1}
                   6659:         }
                   6660:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6661:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6662:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6663:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6664:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6665:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6666:             my $doubleerror = 0;
                   6667:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6668:                    (!$doubleerror)) {
                   6669:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6670:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6671:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6672:                if (length(@currarray) > 2) {
                   6673:                    $doubleerror = 1;
                   6674:                } 
                   6675:             }
                   6676:             if ($doubleerror) {
                   6677:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6678:             }
                   6679:         } else {
                   6680:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6681:         }
                   6682:         my $item = $ansnum;
                   6683:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6684:             $record->{"scantron.$item.answer"} = '';
                   6685:             $item ++;
                   6686:         }
1.447     foxr     6687: 
1.503     raeburn  6688:         my @ans=@array;
                   6689:         my $i=0;
                   6690:         my $increment = 0;
                   6691:         while ($#ans) {
                   6692:             $i+=length($ans[0]) + $increment;
                   6693:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6694:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6695:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6696:             shift(@ans);
                   6697:             $increment = 1;
                   6698:         }
                   6699:         $ansnum += $answers_needed;
1.82      albertel 6700:     }
1.503     raeburn  6701:     return $ansnum;
1.82      albertel 6702: }
                   6703: 
1.423     albertel 6704: =pod
                   6705: 
                   6706: =item scantron_add_delay
                   6707: 
                   6708:    Adds an error message that occurred during the grading phase to a
                   6709:    queue of messages to be shown after grading pass is complete
                   6710: 
                   6711:  Arguments:
1.424     albertel 6712:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6713:    $scanline    - the scanline that caused the error
                   6714:    $errormesage - the error message
                   6715:    $errorcode   - a numeric code for the error
                   6716: 
                   6717:  Side Effects:
1.424     albertel 6718:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6719: 
                   6720: =cut
                   6721: 
1.82      albertel 6722: sub scantron_add_delay {
1.140     albertel 6723:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6724:     push(@$delayqueue,
                   6725: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6726: 	  'ecode' => $errorcode }
                   6727: 	 );
1.82      albertel 6728: }
                   6729: 
1.423     albertel 6730: =pod
                   6731: 
                   6732: =item scantron_find_student
                   6733: 
1.424     albertel 6734:    Finds the username for the current scanline
                   6735: 
                   6736:   Arguments:
                   6737:    $scantron_record - hash result from scantron_parse_scanline
                   6738:    $scan_data       - hash of correction information 
                   6739:                       (see &scantron_getfile() form more information)
                   6740:    $idmap           - hash from &username_to_idmap()
                   6741:    $line            - number of current scanline
                   6742:  
                   6743:   Returns:
                   6744:    Either 'username:domain' or undef if unknown
                   6745: 
1.423     albertel 6746: =cut
                   6747: 
1.82      albertel 6748: sub scantron_find_student {
1.157     albertel 6749:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6750:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6751:     if ($scanID =~ /^\s*$/) {
                   6752:  	return &scan_data($scan_data,"$line.user");
                   6753:     }
1.83      albertel 6754:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6755:  	if (lc($id) eq lc($scanID)) {
                   6756:  	    return $$idmap{$id};
                   6757:  	}
1.83      albertel 6758:     }
                   6759:     return undef;
                   6760: }
                   6761: 
1.423     albertel 6762: =pod
                   6763: 
                   6764: =item scantron_filter
                   6765: 
1.424     albertel 6766:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6767:    hidden resources was selected
                   6768: 
1.423     albertel 6769: =cut
                   6770: 
1.83      albertel 6771: sub scantron_filter {
                   6772:     my ($curres)=@_;
1.331     albertel 6773: 
                   6774:     if (ref($curres) && $curres->is_problem()) {
                   6775: 	# if the user has asked to not have either hidden
                   6776: 	# or 'randomout' controlled resources to be graded
                   6777: 	# don't include them
                   6778: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6779: 	    && $curres->randomout) {
                   6780: 	    return 0;
                   6781: 	}
1.83      albertel 6782: 	return 1;
                   6783:     }
                   6784:     return 0;
1.82      albertel 6785: }
                   6786: 
1.423     albertel 6787: =pod
                   6788: 
                   6789: =item scantron_process_corrections
                   6790: 
1.424     albertel 6791:    Gets correction information out of submitted form data and corrects
                   6792:    the scanline
                   6793: 
1.423     albertel 6794: =cut
                   6795: 
1.157     albertel 6796: sub scantron_process_corrections {
                   6797:     my ($r) = @_;
1.754     raeburn  6798:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6799:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6800:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6801:     my $which=$env{'form.scantron_line'};
1.200     albertel 6802:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6803:     my ($skip,$err,$errmsg);
1.257     albertel 6804:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6805: 	$skip=1;
1.257     albertel 6806:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6807: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6808: 	    $env{'form.scantron_domain'};
1.157     albertel 6809: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6810: 	($line,$err,$errmsg)=
                   6811: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6812: 				     'ID',{'newid'=>$newid,
1.257     albertel 6813: 				    'username'=>$env{'form.scantron_username'},
                   6814: 				    'domain'=>$env{'form.scantron_domain'}});
                   6815:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6816: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6817: 	my $newCODE;
1.192     albertel 6818: 	my %args;
1.190     albertel 6819: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6820: 	    $newCODE='use_unfound';
1.190     albertel 6821: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6822: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6823: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6824: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6825: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6826: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6827: 	}
1.257     albertel 6828: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6829: 	    $args{'CODE_ignore_dup'}=1;
                   6830: 	}
                   6831: 	$args{'CODE'}=$newCODE;
1.186     albertel 6832: 	($line,$err,$errmsg)=
                   6833: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6834: 				     'CODE',\%args);
1.257     albertel 6835:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6836: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6837: 	    ($line,$err,$errmsg)=
                   6838: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6839: 					 $which,'answer',
                   6840: 					 { 'question'=>$question,
1.503     raeburn  6841: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6842:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6843: 	    if ($err) { last; }
                   6844: 	}
                   6845:     }
                   6846:     if ($err) {
1.703     bisitz   6847:         $r->print(
                   6848:             '<p class="LC_error">'
                   6849:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6850:                 $errmsg)
1.704     raeburn  6851:            .'</p>');
1.157     albertel 6852:     } else {
1.200     albertel 6853: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6854: 	&scantron_putfile($scanlines,$scan_data);
                   6855:     }
                   6856: }
                   6857: 
1.423     albertel 6858: =pod
                   6859: 
                   6860: =item reset_skipping_status
                   6861: 
1.424     albertel 6862:    Forgets the current set of remember skipped scanlines (and thus
                   6863:    reverts back to considering all lines in the
                   6864:    scantron_skipped_<filename> file)
                   6865: 
1.423     albertel 6866: =cut
                   6867: 
1.200     albertel 6868: sub reset_skipping_status {
                   6869:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6870:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6871:     &scantron_putfile(undef,$scan_data);
                   6872: }
                   6873: 
1.423     albertel 6874: =pod
                   6875: 
                   6876: =item start_skipping
                   6877: 
1.424     albertel 6878:    Marks a scanline to be skipped. 
                   6879: 
1.423     albertel 6880: =cut
                   6881: 
1.376     albertel 6882: sub start_skipping {
1.200     albertel 6883:     my ($scan_data,$i)=@_;
                   6884:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6885:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6886: 	$remembered{$i}=2;
                   6887:     } else {
                   6888: 	$remembered{$i}=1;
                   6889:     }
1.200     albertel 6890:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6891: }
                   6892: 
1.423     albertel 6893: =pod
                   6894: 
                   6895: =item should_be_skipped
                   6896: 
1.424     albertel 6897:    Checks whether a scanline should be skipped.
                   6898: 
1.423     albertel 6899: =cut
                   6900: 
1.200     albertel 6901: sub should_be_skipped {
1.376     albertel 6902:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6903:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6904: 	# not redoing old skips
1.376     albertel 6905: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6906: 	return 0;
                   6907:     }
                   6908:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6909: 
                   6910:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6911: 	return 0;
                   6912:     }
1.200     albertel 6913:     return 1;
                   6914: }
                   6915: 
1.423     albertel 6916: =pod
                   6917: 
                   6918: =item remember_current_skipped
                   6919: 
1.424     albertel 6920:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6921:    file and remembers them into scan_data for later use.
                   6922: 
1.423     albertel 6923: =cut
                   6924: 
1.200     albertel 6925: sub remember_current_skipped {
                   6926:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6927:     my %to_remember;
                   6928:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6929: 	if ($scanlines->{'skipped'}[$i]) {
                   6930: 	    $to_remember{$i}=1;
                   6931: 	}
                   6932:     }
1.376     albertel 6933: 
1.200     albertel 6934:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6935:     &scantron_putfile(undef,$scan_data);
                   6936: }
                   6937: 
1.423     albertel 6938: =pod
                   6939: 
                   6940: =item check_for_error
                   6941: 
1.424     albertel 6942:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6943:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6944:     something went wrong.
                   6945: 
1.423     albertel 6946: =cut
                   6947: 
1.200     albertel 6948: sub check_for_error {
                   6949:     my ($r,$result)=@_;
                   6950:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6951: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6952:     }
                   6953: }
1.157     albertel 6954: 
1.423     albertel 6955: =pod
                   6956: 
                   6957: =item scantron_warning_screen
                   6958: 
1.424     albertel 6959:    Interstitial screen to make sure the operator has selected the
                   6960:    correct options before we start the validation phase.
                   6961: 
1.423     albertel 6962: =cut
                   6963: 
1.203     albertel 6964: sub scantron_warning_screen {
1.650     raeburn  6965:     my ($button_text,$symb)=@_;
1.257     albertel 6966:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.754     raeburn  6967:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6968:     my $CODElist;
1.284     albertel 6969:     if ($scantron_config{'CODElocation'} &&
                   6970: 	$scantron_config{'CODEstart'} &&
                   6971: 	$scantron_config{'CODElength'}) {
                   6972: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   6973: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6974: 	$CODElist=
1.492     albertel 6975: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6976: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6977:     }
1.663     raeburn  6978:     my $lastbubblepoints;
                   6979:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6980:         $lastbubblepoints =
                   6981:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6982:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6983:     }
1.492     albertel 6984:     return ('
1.203     albertel 6985: <p>
1.492     albertel 6986: <span class="LC_warning">
1.705     raeburn  6987: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6988: </p>
                   6989: <table>
1.492     albertel 6990: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6991: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6992: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6993: </table>
1.680     raeburn  6994: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6995: '.&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.203     albertel 6996: 
                   6997: <br />
1.492     albertel 6998: ');
1.203     albertel 6999: }
                   7000: 
1.423     albertel 7001: =pod
                   7002: 
                   7003: =item scantron_do_warning
                   7004: 
1.424     albertel 7005:    Check if the operator has picked something for all required
                   7006:    fields. Error out if something is missing.
                   7007: 
1.423     albertel 7008: =cut
                   7009: 
1.203     albertel 7010: sub scantron_do_warning {
1.608     www      7011:     my ($r,$symb)=@_;
1.203     albertel 7012:     if (!$symb) {return '';}
1.324     albertel 7013:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7014:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7015:     if ( $env{'form.selectpage'} eq '' ||
                   7016: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7017: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  7018: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7019: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7020: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7021: 	} 
1.257     albertel 7022: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  7023: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
1.237     albertel 7024: 	} 
1.257     albertel 7025: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  7026: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
1.237     albertel 7027: 	} 
                   7028:     } else {
1.650     raeburn  7029: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  7030:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7031: 	$r->print('
1.663     raeburn  7032: '.$warning.$bubbledbyhand.'
1.492     albertel 7033: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7034: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7035: ');
1.237     albertel 7036:     }
1.614     www      7037:     $r->print("</form><br />");
1.203     albertel 7038:     return '';
                   7039: }
                   7040: 
1.423     albertel 7041: =pod
                   7042: 
                   7043: =item scantron_form_start
                   7044: 
1.424     albertel 7045:     html hidden input for remembering all selected grading options
                   7046: 
1.423     albertel 7047: =cut
                   7048: 
1.203     albertel 7049: sub scantron_form_start {
                   7050:     my ($max_bubble)=@_;
                   7051:     my $result= <<SCANTRONFORM;
                   7052: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7053:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7054:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7055:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7056:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7057:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7058:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7059:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7060:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7061:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7062: SCANTRONFORM
1.447     foxr     7063: 
                   7064:   my $line = 0;
                   7065:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7066:        my $chunk =
                   7067: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7068:        $chunk .=
                   7069: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7070:        $chunk .= 
                   7071:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7072:        $chunk .=
                   7073:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  7074:        $chunk .=
                   7075:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7076:        $result .= $chunk;
                   7077:        $line++;
1.691     raeburn  7078:     }
1.203     albertel 7079:     return $result;
                   7080: }
                   7081: 
1.423     albertel 7082: =pod
                   7083: 
                   7084: =item scantron_validate_file
                   7085: 
1.659     raeburn  7086:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7087: 
                   7088:     Also processes any necessary information resets that need to
                   7089:     occur before validation begins (ignore previous corrections,
                   7090:     restarting the skipped records processing)
                   7091: 
1.423     albertel 7092: =cut
                   7093: 
1.157     albertel 7094: sub scantron_validate_file {
1.608     www      7095:     my ($r,$symb) = @_;
1.157     albertel 7096:     if (!$symb) {return '';}
1.324     albertel 7097:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7098:     
1.703     bisitz   7099:     # do the detection of only doing skipped records first before we delete
1.424     albertel 7100:     # them when doing the corrections reset
1.257     albertel 7101:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7102: 	&reset_skipping_status();
                   7103:     }
1.257     albertel 7104:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7105: 	&remember_current_skipped();
1.257     albertel 7106: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7107:     }
                   7108: 
1.257     albertel 7109:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7110: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7111: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7112: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7113: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7114:     }
1.200     albertel 7115: 
1.257     albertel 7116:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7117: 	&scantron_process_corrections($r);
                   7118:     }
1.503     raeburn  7119:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7120:     #get the student pick code ready
                   7121:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7122:     my $nav_error;
1.754     raeburn  7123:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  7124:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7125:     if ($nav_error) {
                   7126:         $r->print(&navmap_errormsg());
                   7127:         return '';
                   7128:     }
1.203     albertel 7129:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  7130:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7131:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7132:     }
1.157     albertel 7133:     $r->print($result);
                   7134:     
1.334     albertel 7135:     my @validate_phases=( 'sequence',
                   7136: 			  'ID',
1.157     albertel 7137: 			  'CODE',
                   7138: 			  'doublebubble',
                   7139: 			  'missingbubbles');
1.257     albertel 7140:     if (!$env{'form.validatepass'}) {
                   7141: 	$env{'form.validatepass'} = 0;
1.157     albertel 7142:     }
1.257     albertel 7143:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7144: 
1.448     foxr     7145: 
1.157     albertel 7146:     my $stop=0;
                   7147:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7148: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7149: 	$r->rflush();
1.691     raeburn  7150:      
1.157     albertel 7151: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7152: 	{
                   7153: 	    no strict 'refs';
                   7154: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7155: 	}
                   7156:     }
                   7157:     if (!$stop) {
1.650     raeburn  7158: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  7159: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7160:                   $warning.
                   7161:                   &mt('Perform verification for each student after storage of submissions?').
                   7162:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7163:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7164:                   ('&nbsp;'x3).'<label>'.
                   7165:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7166:                   '</label></span><br />'.
                   7167:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  7168:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  7169:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7170:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7171:     } else {
                   7172: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7173: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7174:     }
                   7175:     if ($stop) {
1.334     albertel 7176: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7177: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7178: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7179: 
1.650     raeburn  7180: 	    $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 7181: 	} else {
1.503     raeburn  7182:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7183: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7184:             } else {
1.539     riegler  7185:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7186:             }
1.492     albertel 7187: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7188: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7189: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7190: 	}
1.157     albertel 7191:     }
1.614     www      7192:     $r->print(" </form><br />");
1.157     albertel 7193:     return '';
                   7194: }
                   7195: 
1.423     albertel 7196: 
                   7197: =pod
                   7198: 
                   7199: =item scantron_remove_file
                   7200: 
1.659     raeburn  7201:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7202:    scantron_original_<filename> is never removed
                   7203: 
                   7204: 
1.423     albertel 7205: =cut
                   7206: 
1.200     albertel 7207: sub scantron_remove_file {
1.192     albertel 7208:     my ($which)=@_;
1.257     albertel 7209:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7210:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7211:     my $file='scantron_';
1.200     albertel 7212:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7213: 	$file.=$which.'_';
1.192     albertel 7214:     } else {
                   7215: 	return 'refused';
                   7216:     }
1.257     albertel 7217:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7218:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7219: }
                   7220: 
1.423     albertel 7221: 
                   7222: =pod
                   7223: 
                   7224: =item scantron_remove_scan_data
                   7225: 
1.659     raeburn  7226:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7227:    data file.  (In the case that both the are doing skipped records we need
                   7228:    to remember the old skipped lines for the time being so that element
                   7229:    persists for a while.)
                   7230: 
1.423     albertel 7231: =cut
                   7232: 
1.200     albertel 7233: sub scantron_remove_scan_data {
1.257     albertel 7234:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7235:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7236:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7237:     my @todelete;
1.257     albertel 7238:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7239:     foreach my $key (@keys) {
                   7240: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7241: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7242: 		$key=~/remember_skipping/) {
                   7243: 		next;
                   7244: 	    }
1.192     albertel 7245: 	    push(@todelete,$key);
                   7246: 	}
                   7247:     }
1.200     albertel 7248:     my $result;
1.192     albertel 7249:     if (@todelete) {
1.491     albertel 7250: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7251: 				       \@todelete,$cdom,$cname);
                   7252:     } else {
                   7253: 	$result = 'ok';
1.192     albertel 7254:     }
                   7255:     return $result;
                   7256: }
                   7257: 
1.423     albertel 7258: 
                   7259: =pod
                   7260: 
                   7261: =item scantron_getfile
                   7262: 
1.659     raeburn  7263:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7264:     the scan_data hash
                   7265:   
                   7266:   Arguments:
                   7267:     None
                   7268: 
                   7269:   Returns:
                   7270:     2 hash references
                   7271: 
                   7272:      - first one has 
                   7273:          orig      -
                   7274:          corrected -
                   7275:          skipped   -  each of which points to an array ref of the specified
                   7276:                       file broken up into individual lines
                   7277:          count     - number of scanlines
                   7278:  
                   7279:      - second is the scan_data hash possible keys are
1.425     albertel 7280:        ($number refers to scanline numbered $number and thus the key affects
                   7281:         only that scanline
                   7282:         $bubline refers to the specific bubble line element and the aspects
                   7283:         refers to that specific bubble line element)
                   7284: 
                   7285:        $number.user - username:domain to use
                   7286:        $number.CODE_ignore_dup 
                   7287:                     - ignore the duplicate CODE error 
                   7288:        $number.useCODE
                   7289:                     - use the CODE in the scanline as is
                   7290:        $number.no_bubble.$bubline
                   7291:                     - it is valid that there is no bubbled in bubble
                   7292:                       at $number $bubline
                   7293:        remember_skipping
                   7294:                     - a frozen hash containing keys of $number and values
                   7295:                       of either 
                   7296:                         1 - we are on a 'do skipped records pass' and plan
                   7297:                             on processing this line
                   7298:                         2 - we are on a 'do skipped records pass' and this
                   7299:                             scanline has been marked to skip yet again
1.424     albertel 7300: 
1.423     albertel 7301: =cut
                   7302: 
1.157     albertel 7303: sub scantron_getfile {
1.200     albertel 7304:     #FIXME really would prefer a scantron directory
1.257     albertel 7305:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7306:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7307:     my $lines;
                   7308:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7309: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7310:     my %scanlines;
                   7311:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7312:     my $temp=$scanlines{'orig'};
                   7313:     $scanlines{'count'}=$#$temp;
                   7314: 
                   7315:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7316: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7317:     if ($lines eq '-1') {
                   7318: 	$scanlines{'corrected'}=[];
                   7319:     } else {
                   7320: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7321:     }
                   7322:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7323: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7324:     if ($lines eq '-1') {
                   7325: 	$scanlines{'skipped'}=[];
                   7326:     } else {
                   7327: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7328:     }
1.175     albertel 7329:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7330:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7331:     my %scan_data = @tmp;
                   7332:     return (\%scanlines,\%scan_data);
                   7333: }
                   7334: 
1.423     albertel 7335: =pod
                   7336: 
                   7337: =item lonnet_putfile
                   7338: 
1.424     albertel 7339:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7340: 
                   7341:  Arguments:
                   7342:    $contents - data to store
                   7343:    $filename - filename to store $contents into
                   7344: 
                   7345:  Returns:
                   7346:    result value from &Apache::lonnet::finishuserfileupload
                   7347: 
1.423     albertel 7348: =cut
                   7349: 
1.157     albertel 7350: sub lonnet_putfile {
                   7351:     my ($contents,$filename)=@_;
1.257     albertel 7352:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7353:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7354:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7355:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7356: 
                   7357: }
                   7358: 
1.423     albertel 7359: =pod
                   7360: 
                   7361: =item scantron_putfile
                   7362: 
1.659     raeburn  7363:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7364:     scan_data hash. (Does not modify the original version only the
                   7365:     corrected and skipped versions.
                   7366: 
                   7367:  Arguments:
                   7368:     $scanlines - hash ref that looks like the first return value from
                   7369:                  &scantron_getfile()
                   7370:     $scan_data - hash ref that looks like the second return value from
                   7371:                  &scantron_getfile()
                   7372: 
1.423     albertel 7373: =cut
                   7374: 
1.157     albertel 7375: sub scantron_putfile {
                   7376:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7377:     #FIXME really would prefer a scantron directory
1.257     albertel 7378:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7379:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7380:     if ($scanlines) {
                   7381: 	my $prefix='scantron_';
1.157     albertel 7382: # no need to update orig, shouldn't change
                   7383: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7384: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7385: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7386: 			$prefix.'corrected_'.
1.257     albertel 7387: 			$env{'form.scantron_selectfile'});
1.200     albertel 7388: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7389: 			$prefix.'skipped_'.
1.257     albertel 7390: 			$env{'form.scantron_selectfile'});
1.200     albertel 7391:     }
1.175     albertel 7392:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7393: }
                   7394: 
1.423     albertel 7395: =pod
                   7396: 
                   7397: =item scantron_get_line
                   7398: 
1.424     albertel 7399:    Returns the correct version of the scanline
                   7400: 
                   7401:  Arguments:
                   7402:     $scanlines - hash ref that looks like the first return value from
                   7403:                  &scantron_getfile()
                   7404:     $scan_data - hash ref that looks like the second return value from
                   7405:                  &scantron_getfile()
                   7406:     $i         - number of the requested line (starts at 0)
                   7407: 
                   7408:  Returns:
                   7409:    A scanline, (either the original or the corrected one if it
                   7410:    exists), or undef if the requested scanline should be
                   7411:    skipped. (Either because it's an skipped scanline, or it's an
                   7412:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7413:    pass.
                   7414: 
1.423     albertel 7415: =cut
                   7416: 
1.157     albertel 7417: sub scantron_get_line {
1.200     albertel 7418:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7419:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7420:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7421:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7422:     return $scanlines->{'orig'}[$i]; 
                   7423: }
                   7424: 
1.423     albertel 7425: =pod
                   7426: 
                   7427: =item scantron_todo_count
                   7428: 
1.424     albertel 7429:     Counts the number of scanlines that need processing.
                   7430: 
                   7431:  Arguments:
                   7432:     $scanlines - hash ref that looks like the first return value from
                   7433:                  &scantron_getfile()
                   7434:     $scan_data - hash ref that looks like the second return value from
                   7435:                  &scantron_getfile()
                   7436: 
                   7437:  Returns:
                   7438:     $count - number of scanlines to process
                   7439: 
1.423     albertel 7440: =cut
                   7441: 
1.200     albertel 7442: sub get_todo_count {
                   7443:     my ($scanlines,$scan_data)=@_;
                   7444:     my $count=0;
                   7445:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7446: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7447: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7448: 	$count++;
                   7449:     }
                   7450:     return $count;
                   7451: }
                   7452: 
1.423     albertel 7453: =pod
                   7454: 
                   7455: =item scantron_put_line
                   7456: 
1.659     raeburn  7457:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7458:     data file.
                   7459: 
                   7460:  Arguments:
                   7461:     $scanlines - hash ref that looks like the first return value from
                   7462:                  &scantron_getfile()
                   7463:     $scan_data - hash ref that looks like the second return value from
                   7464:                  &scantron_getfile()
                   7465:     $i         - line number to update
                   7466:     $newline   - contents of the updated scanline
                   7467:     $skip      - if true make the line for skipping and update the
                   7468:                  'skipped' file
                   7469: 
1.423     albertel 7470: =cut
                   7471: 
1.157     albertel 7472: sub scantron_put_line {
1.200     albertel 7473:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7474:     if ($skip) {
                   7475: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7476: 	&start_skipping($scan_data,$i);
1.157     albertel 7477: 	return;
                   7478:     }
                   7479:     $scanlines->{'corrected'}[$i]=$newline;
                   7480: }
                   7481: 
1.423     albertel 7482: =pod
                   7483: 
                   7484: =item scantron_clear_skip
                   7485: 
1.424     albertel 7486:    Remove a line from the 'skipped' file
                   7487: 
                   7488:  Arguments:
                   7489:     $scanlines - hash ref that looks like the first return value from
                   7490:                  &scantron_getfile()
                   7491:     $scan_data - hash ref that looks like the second return value from
                   7492:                  &scantron_getfile()
                   7493:     $i         - line number to update
                   7494: 
1.423     albertel 7495: =cut
                   7496: 
1.376     albertel 7497: sub scantron_clear_skip {
                   7498:     my ($scanlines,$scan_data,$i)=@_;
                   7499:     if (exists($scanlines->{'skipped'}[$i])) {
                   7500: 	undef($scanlines->{'skipped'}[$i]);
                   7501: 	return 1;
                   7502:     }
                   7503:     return 0;
                   7504: }
                   7505: 
1.423     albertel 7506: =pod
                   7507: 
                   7508: =item scantron_filter_not_exam
                   7509: 
1.424     albertel 7510:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7511:    filter out resources that are not marked as 'exam' mode
                   7512: 
1.423     albertel 7513: =cut
                   7514: 
1.334     albertel 7515: sub scantron_filter_not_exam {
                   7516:     my ($curres)=@_;
                   7517:     
                   7518:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7519: 	# if the user has asked to not have either hidden
                   7520: 	# or 'randomout' controlled resources to be graded
                   7521: 	# don't include them
                   7522: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7523: 	    && $curres->randomout) {
                   7524: 	    return 0;
                   7525: 	}
                   7526: 	return 1;
                   7527:     }
                   7528:     return 0;
                   7529: }
                   7530: 
1.423     albertel 7531: =pod
                   7532: 
                   7533: =item scantron_validate_sequence
                   7534: 
1.424     albertel 7535:     Validates the selected sequence, checking for resource that are
                   7536:     not set to exam mode.
                   7537: 
1.423     albertel 7538: =cut
                   7539: 
1.334     albertel 7540: sub scantron_validate_sequence {
                   7541:     my ($r,$currentphase) = @_;
                   7542: 
                   7543:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7544:     unless (ref($navmap)) {
                   7545:         $r->print(&navmap_errormsg());
                   7546:         return (1,$currentphase);
                   7547:     }
1.334     albertel 7548:     my (undef,undef,$sequence)=
                   7549: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7550: 
                   7551:     my $map=$navmap->getResourceByUrl($sequence);
                   7552: 
                   7553:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7554:                                     value="ignore" />');
                   7555:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7556: 	my @resources=
                   7557: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7558: 	if (@resources) {
1.675     bisitz   7559: 	    $r->print(
                   7560:                 '<p class="LC_warning">'
                   7561:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7562:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7563:                    .' work correctly.')
                   7564:                .'</p>'
                   7565:             );
1.334     albertel 7566: 	    return (1,$currentphase);
                   7567: 	}
                   7568:     }
                   7569: 
                   7570:     return (0,$currentphase+1);
                   7571: }
                   7572: 
1.423     albertel 7573: 
                   7574: 
1.157     albertel 7575: sub scantron_validate_ID {
                   7576:     my ($r,$currentphase) = @_;
                   7577:     
                   7578:     #get student info
                   7579:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7580:     my %idmap=&username_to_idmap($classlist);
                   7581: 
                   7582:     #get scantron line setup
1.754     raeburn  7583:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7584:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7585: 
                   7586:     my $nav_error;
1.649     raeburn  7587:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7588:     if ($nav_error) {
                   7589:         $r->print(&navmap_errormsg());
                   7590:         return(1,$currentphase);
                   7591:     }
1.157     albertel 7592: 
                   7593:     my %found=('ids'=>{},'usernames'=>{});
                   7594:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7595: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7596: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7597: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7598: 						 $scan_data);
                   7599: 	my $id=$$scan_record{'scantron.ID'};
                   7600: 	my $found;
                   7601: 	foreach my $checkid (keys(%idmap)) {
                   7602: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7603: 	}
                   7604: 	if ($found) {
                   7605: 	    my $username=$idmap{$found};
                   7606: 	    if ($found{'ids'}{$found}) {
                   7607: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7608: 					 $line,'duplicateID',$found);
1.194     albertel 7609: 		return(1,$currentphase);
1.157     albertel 7610: 	    } elsif ($found{'usernames'}{$username}) {
                   7611: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7612: 					 $line,'duplicateID',$username);
1.194     albertel 7613: 		return(1,$currentphase);
1.157     albertel 7614: 	    }
1.186     albertel 7615: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7616: 	    $found{'ids'}{$found}++;
                   7617: 	    $found{'usernames'}{$username}++;
                   7618: 	} else {
                   7619: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7620: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7621: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7622: 		    &scantron_get_correction($r,$i,$scan_record,
                   7623: 					     \%scantron_config,
                   7624: 					     $line,'duplicateID',$username);
1.194     albertel 7625: 		    return(1,$currentphase);
1.157     albertel 7626: 		} elsif (!defined($username)) {
                   7627: 		    &scantron_get_correction($r,$i,$scan_record,
                   7628: 					     \%scantron_config,
                   7629: 					     $line,'incorrectID');
1.194     albertel 7630: 		    return(1,$currentphase);
1.157     albertel 7631: 		}
                   7632: 		$found{'usernames'}{$username}++;
                   7633: 	    } else {
                   7634: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7635: 					 $line,'incorrectID');
1.194     albertel 7636: 		return(1,$currentphase);
1.157     albertel 7637: 	    }
                   7638: 	}
                   7639:     }
                   7640: 
                   7641:     return (0,$currentphase+1);
                   7642: }
                   7643: 
1.423     albertel 7644: 
1.157     albertel 7645: sub scantron_get_correction {
1.691     raeburn  7646:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7647:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7648: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7649: #to show both the current line and the previous one and allow skipping
                   7650: #the previous one or the current one
                   7651: 
1.333     albertel 7652:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7653:         $r->print(
                   7654:             '<p class="LC_warning">'
                   7655:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7656:                 "<b>$error</b>",
                   7657:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7658:            ."</p> \n");
1.157     albertel 7659:     } else {
1.658     bisitz   7660:         $r->print(
                   7661:             '<p class="LC_warning">'
                   7662:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7663:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7664:            ."</p> \n");
                   7665:     }
                   7666:     my $message =
                   7667:         '<p>'
                   7668:        .&mt('The ID on the form is [_1]',
                   7669:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7670:        .'<br />'
1.665     raeburn  7671:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7672:             $$scan_record{'scantron.LastName'},
                   7673:             $$scan_record{'scantron.FirstName'})
                   7674:        .'</p>';
1.242     albertel 7675: 
1.157     albertel 7676:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7677:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7678:                            # Array populated for doublebubble or
                   7679:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7680:                            # to validate radio button checking   
                   7681: 
1.157     albertel 7682:     if ($error =~ /ID$/) {
1.186     albertel 7683: 	if ($error eq 'incorrectID') {
1.658     bisitz   7684:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7685: 		      "</p>\n");
1.157     albertel 7686: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7687:             $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 7688: 	}
1.242     albertel 7689: 	$r->print($message);
1.492     albertel 7690: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7691: 	$r->print("\n<ul><li> ");
                   7692: 	#FIXME it would be nice if this sent back the user ID and
                   7693: 	#could do partial userID matches
                   7694: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7695: 				       'scantron_username','scantron_domain'));
                   7696: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7697: 	$r->print("\n:\n".
1.257     albertel 7698: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7699: 
                   7700: 	$r->print('</li>');
1.186     albertel 7701:     } elsif ($error =~ /CODE$/) {
                   7702: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7703: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7704: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7705: 	    $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 7706: 	}
1.658     bisitz   7707: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7708: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7709:                  ."</p>\n");
1.242     albertel 7710: 	$r->print($message);
1.658     bisitz   7711: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7712: 	$r->print("\n<br /> ");
1.194     albertel 7713: 	my $i=0;
1.273     albertel 7714: 	if ($error eq 'incorrectCODE' 
                   7715: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7716: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7717: 	    if ($closest > 0) {
                   7718: 		foreach my $testcode (@{$closest}) {
                   7719: 		    my $checked='';
1.569     bisitz   7720: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7721: 		    $r->print("
                   7722:    <label>
1.569     bisitz   7723:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7724:        ".&mt("Use the similar CODE [_1] instead.",
                   7725: 	    "<b><tt>".$testcode."</tt></b>")."
                   7726:     </label>
                   7727:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7728: 		    $r->print("\n<br />");
                   7729: 		    $i++;
                   7730: 		}
1.194     albertel 7731: 	    }
                   7732: 	}
1.273     albertel 7733: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7734: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7735: 	    $r->print("
                   7736:     <label>
1.569     bisitz   7737:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7738:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7739: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7740:     </label>");
1.273     albertel 7741: 	    $r->print("\n<br />");
                   7742: 	}
1.194     albertel 7743: 
1.597     wenzelju 7744: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7745: function change_radio(field) {
1.190     albertel 7746:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7747:     var i;
                   7748:     for (i=0;i<slct.length;i++) {
                   7749:         if (slct[i].value==field) { slct[i].checked=true; }
                   7750:     }
                   7751: }
                   7752: ENDSCRIPT
1.187     albertel 7753: 	my $href="/adm/pickcode?".
1.359     www      7754: 	   "form=".&escape("scantronupload").
                   7755: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7756: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7757: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7758: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7759: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7760: 	    $r->print("
                   7761:     <label>
                   7762:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7763:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7764: 	     "<a target='_blank' href='$href'>","</a>")."
                   7765:     </label> 
1.558     bisitz   7766:     ".&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 7767: 	    $r->print("\n<br />");
                   7768: 	}
1.492     albertel 7769: 	$r->print("
                   7770:     <label>
                   7771:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7772:        ".&mt("Use [_1] as the CODE.",
                   7773: 	     "</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 7774: 	$r->print("\n<br /><br />");
1.157     albertel 7775:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7776: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7777: 
                   7778: 	# The form field scantron_questions is acutally a list of line numbers.
                   7779: 	# represented by this form so:
                   7780: 
1.691     raeburn  7781: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7782:                                                 $respnumlookup,$startline);
1.497     foxr     7783: 
1.157     albertel 7784: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7785: 		  $line_list.'" />');
1.242     albertel 7786: 	$r->print($message);
1.492     albertel 7787: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7788: 	foreach my $question (@{$arg}) {
1.503     raeburn  7789: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7790:                                                    $scan_record, $error,
                   7791:                                                    $randomorder,$randompick,
                   7792:                                                    $respnumlookup,$startline);
1.524     raeburn  7793:             push(@lines_to_correct,@linenums);
1.157     albertel 7794: 	}
1.503     raeburn  7795:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7796:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7797: 	$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 7798: 	$r->print($message);
1.492     albertel 7799: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7800: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7801: 
1.503     raeburn  7802: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7803: 	# a list of question numbers. Therefore:
                   7804: 	#
1.691     raeburn  7805: 
                   7806: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7807:                                                 $respnumlookup,$startline);
1.497     foxr     7808: 
1.157     albertel 7809: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7810: 		  $line_list.'" />');
1.157     albertel 7811: 	foreach my $question (@{$arg}) {
1.503     raeburn  7812: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7813:                                                    $scan_record, $error,
                   7814:                                                    $randomorder,$randompick,
                   7815:                                                    $respnumlookup,$startline);
1.524     raeburn  7816:             push(@lines_to_correct,@linenums);
1.157     albertel 7817: 	}
1.503     raeburn  7818:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7819:     } else {
                   7820: 	$r->print("\n<ul>");
                   7821:     }
                   7822:     $r->print("\n</li></ul>");
1.497     foxr     7823: }
                   7824: 
1.503     raeburn  7825: sub verify_bubbles_checked {
                   7826:     my (@ansnums) = @_;
                   7827:     my $ansnumstr = join('","',@ansnums);
                   7828:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.736     damieng  7829:     &js_escape(\$warning);
1.597     wenzelju 7830:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7831: function verify_bubble_radio(form) {
                   7832:     var ansnumArray = new Array ("$ansnumstr");
                   7833:     var need_bubble_count = 0;
                   7834:     for (var i=0; i<ansnumArray.length; i++) {
                   7835:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7836:             var bubble_picked = 0; 
                   7837:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7838:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7839:                     bubble_picked = 1;
                   7840:                 }
                   7841:             }
                   7842:             if (bubble_picked == 0) {
                   7843:                 need_bubble_count ++;
                   7844:             }
                   7845:         }
                   7846:     }
                   7847:     if (need_bubble_count) {
                   7848:         alert("$warning");
                   7849:         return;
                   7850:     }
                   7851:     form.submit(); 
                   7852: }
                   7853: ENDSCRIPT
                   7854:     return $output;
                   7855: }
                   7856: 
1.497     foxr     7857: =pod
                   7858: 
                   7859: =item  questions_to_line_list
1.157     albertel 7860: 
1.497     foxr     7861: Converts a list of questions into a string of comma separated
                   7862: line numbers in the answer sheet used by the questions.  This is
                   7863: used to fill in the scantron_questions form field.
                   7864: 
                   7865:   Arguments:
                   7866:      questions    - Reference to an array of questions.
1.691     raeburn  7867:      randomorder  - True if randomorder in use.
                   7868:      randompick   - True if randompick in use.
                   7869:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7870:                      for current line to question number used for same question
                   7871:                      in "Master Seqence" (as seen by Course Coordinator).
                   7872:      startline    - Reference to hash where key is question number (0 is first)
                   7873:                     and key is number of first bubble line for current student
                   7874:                     or code-based randompick and/or randomorder.
1.693     raeburn  7875: 
1.497     foxr     7876: =cut
                   7877: 
                   7878: 
                   7879: sub questions_to_line_list {
1.691     raeburn  7880:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7881:     my @lines;
                   7882: 
1.503     raeburn  7883:     foreach my $item (@{$questions}) {
                   7884:         my $question = $item;
                   7885:         my ($first,$count,$last);
                   7886:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7887:             $question = $1;
                   7888:             my $subquestion = $2;
1.691     raeburn  7889:             my $responsenum = $question-1;
                   7890:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7891:                 $responsenum = $respnumlookup->{$question-1};
                   7892:                 if (ref($startline) eq 'HASH') {
                   7893:                     $first = $startline->{$question-1} + 1;
                   7894:                 }
                   7895:             } else {
                   7896:                 $first = $first_bubble_line{$responsenum} + 1;
                   7897:             }
                   7898:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7899:             my $subcount = 1;
                   7900:             while ($subcount<$subquestion) {
                   7901:                 $first += $subans[$subcount-1];
                   7902:                 $subcount ++;
                   7903:             }
                   7904:             $count = $subans[$subquestion-1];
                   7905:         } else {
1.691     raeburn  7906:             my $responsenum = $question-1;
                   7907:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7908:                 $responsenum = $respnumlookup->{$question-1};
                   7909:                 if (ref($startline) eq 'HASH') {
                   7910:                     $first = $startline->{$question-1} + 1;
                   7911:                 }
                   7912:             } else {
                   7913:                 $first = $first_bubble_line{$responsenum} + 1;
                   7914:             }
                   7915: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7916:         }
1.506     raeburn  7917:         $last = $first+$count-1;
1.503     raeburn  7918:         push(@lines, ($first..$last));
1.497     foxr     7919:     }
                   7920:     return join(',', @lines);
                   7921: }
                   7922: 
                   7923: =pod 
                   7924: 
                   7925: =item prompt_for_corrections
                   7926: 
                   7927: Prompts for a potentially multiline correction to the
                   7928: user's bubbling (factors out common code from scantron_get_correction
                   7929: for multi and missing bubble cases).
                   7930: 
                   7931:  Arguments:
                   7932:    $r           - Apache request object.
                   7933:    $question    - The question number to prompt for.
                   7934:    $scan_config - The scantron file configuration hash.
                   7935:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7936:    $error       - Type of error
1.691     raeburn  7937:    $randomorder - True if randomorder in use.
                   7938:    $randompick  - True if randompick in use.
                   7939:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7940:                     for current line to question number used for same question
                   7941:                     in "Master Seqence" (as seen by Course Coordinator).
                   7942:    $startline   - Reference to hash where key is question number (0 is first)
                   7943:                   and value is number of first bubble line for current student
                   7944:                   or code-based randompick and/or randomorder.
                   7945: 
1.497     foxr     7946: 
                   7947:  Implicit inputs:
                   7948:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7949:                                   Numbered from 0 (but question numbers are from
                   7950:                                   1.
                   7951:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7952:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7953:                                   type problems render as separate sub-questions, 
1.503     raeburn  7954:                                   in exam mode. This hash contains a 
                   7955:                                   comma-separated list of the lines per 
                   7956:                                   sub-question.
1.510     raeburn  7957:    %responsetype_per_response   - essayresponse, formularesponse,
                   7958:                                   stringresponse, imageresponse, reactionresponse,
                   7959:                                   and organicresponse type problem parts can have
1.503     raeburn  7960:                                   multiple lines per response if the weight
                   7961:                                   assigned exceeds 10.  In this case, only
                   7962:                                   one bubble per line is permitted, but more 
                   7963:                                   than one line might contain bubbles, e.g.
                   7964:                                   bubbling of: line 1 - J, line 2 - J, 
                   7965:                                   line 3 - B would assign 22 points.  
1.497     foxr     7966: 
                   7967: =cut
                   7968: 
                   7969: sub prompt_for_corrections {
1.691     raeburn  7970:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7971:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7972:     my ($current_line,$lines);
                   7973:     my @linenums;
                   7974:     my $questionnum = $question;
1.691     raeburn  7975:     my ($first,$responsenum);
1.503     raeburn  7976:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7977:         $question = $1;
                   7978:         my $subquestion = $2;
1.691     raeburn  7979:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7980:             $responsenum = $respnumlookup->{$question-1};
                   7981:             if (ref($startline) eq 'HASH') {
                   7982:                 $first = $startline->{$question-1};
                   7983:             }
                   7984:         } else {
                   7985:             $responsenum = $question-1;
1.714     raeburn  7986:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7987:         }
                   7988:         $current_line = $first + 1 ;
                   7989:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7990:         my $subcount = 1;
                   7991:         while ($subcount<$subquestion) {
                   7992:             $current_line += $subans[$subcount-1];
                   7993:             $subcount ++;
                   7994:         }
                   7995:         $lines = $subans[$subquestion-1];
                   7996:     } else {
1.691     raeburn  7997:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7998:             $responsenum = $respnumlookup->{$question-1};
                   7999:             if (ref($startline) eq 'HASH') { 
                   8000:                 $first = $startline->{$question-1};
                   8001:             }
                   8002:         } else {
                   8003:             $responsenum = $question-1;
                   8004:             $first = $first_bubble_line{$responsenum};
                   8005:         }
                   8006:         $current_line = $first + 1;
                   8007:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8008:     }
1.497     foxr     8009:     if ($lines > 1) {
1.503     raeburn  8010:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  8011:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8012:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8013:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8014:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8015:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8016:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   8017:             $r->print(
                   8018:                 &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)
                   8019:                .'<br /><br />'
                   8020:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   8021:                .'<br />'
                   8022:                .&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.')
                   8023:                .'<br />'
                   8024:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   8025:                .'<br /><br />'
                   8026:             );
1.503     raeburn  8027:         } else {
                   8028:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8029:         }
1.497     foxr     8030:     }
                   8031:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8032:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  8033: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8034: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8035:         push(@linenums,$current_line);
1.497     foxr     8036: 	$current_line++;
                   8037:     }
                   8038:     if ($lines > 1) {
                   8039: 	$r->print("<hr /><br />");
                   8040:     }
1.503     raeburn  8041:     return @linenums;
1.157     albertel 8042: }
1.423     albertel 8043: 
                   8044: =pod
                   8045: 
                   8046: =item scantron_bubble_selector
                   8047:   
                   8048:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8049:    possibly showing the existing the selected bubbles if known
1.423     albertel 8050: 
                   8051:  Arguments:
                   8052:     $r           - Apache request object
1.754     raeburn  8053:     $scan_config - hash from &Apache::lonnet::get_scantron_config()
1.497     foxr     8054:     $line        - Number of the line being displayed.
1.503     raeburn  8055:     $questionnum - Question number (may include subquestion)
                   8056:     $error       - Type of error.
1.497     foxr     8057:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8058: 
                   8059: =cut
                   8060: 
1.157     albertel 8061: sub scantron_bubble_selector {
1.503     raeburn  8062:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8063:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8064: 
                   8065:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  8066:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   8067:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8068:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8069:             $max=$$scan_config{'BubblesPerRow'};
                   8070:             if (($scmode eq 'number') && ($max > 10)) {
                   8071:                 $max = 10;
                   8072:             } elsif (($scmode eq 'letter') && $max > 26) {
                   8073:                 $max = 26;
                   8074:             }
                   8075:         } else {
                   8076:             $max = 10;
                   8077:         }
                   8078:     }
1.274     albertel 8079: 
1.157     albertel 8080:     my @alphabet=('A'..'Z');
1.503     raeburn  8081:     $r->print(&Apache::loncommon::start_data_table().
                   8082:               &Apache::loncommon::start_data_table_row());
                   8083:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8084:     for (my $i=0;$i<$max+1;$i++) {
                   8085: 	$r->print("\n".'<td align="center">');
                   8086: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8087: 	else { $r->print('&nbsp;'); }
                   8088: 	$r->print('</td>');
                   8089:     }
1.503     raeburn  8090:     $r->print(&Apache::loncommon::end_data_table_row().
                   8091:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8092:     for (my $i=0;$i<$max;$i++) {
                   8093: 	$r->print("\n".
                   8094: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8095: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8096:     }
1.503     raeburn  8097:     my $nobub_checked = ' ';
                   8098:     if ($error eq 'missingbubble') {
                   8099:         $nobub_checked = ' checked = "checked" ';
                   8100:     }
                   8101:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8102: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8103:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8104:               $line.'" value="'.$questionnum.'" /></td>');
                   8105:     $r->print(&Apache::loncommon::end_data_table_row().
                   8106:               &Apache::loncommon::end_data_table());
1.157     albertel 8107: }
                   8108: 
1.423     albertel 8109: =pod
                   8110: 
                   8111: =item num_matches
                   8112: 
1.424     albertel 8113:    Counts the number of characters that are the same between the two arguments.
                   8114: 
                   8115:  Arguments:
                   8116:    $orig - CODE from the scanline
                   8117:    $code - CODE to match against
                   8118: 
                   8119:  Returns:
                   8120:    $count - integer count of the number of same characters between the
                   8121:             two arguments
                   8122: 
1.423     albertel 8123: =cut
                   8124: 
1.194     albertel 8125: sub num_matches {
                   8126:     my ($orig,$code) = @_;
                   8127:     my @code=split(//,$code);
                   8128:     my @orig=split(//,$orig);
                   8129:     my $same=0;
                   8130:     for (my $i=0;$i<scalar(@code);$i++) {
                   8131: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8132:     }
                   8133:     return $same;
                   8134: }
                   8135: 
1.423     albertel 8136: =pod
                   8137: 
                   8138: =item scantron_get_closely_matching_CODEs
                   8139: 
1.424     albertel 8140:    Cycles through all CODEs and finds the set that has the greatest
                   8141:    number of same characters as the provided CODE
                   8142: 
                   8143:  Arguments:
                   8144:    $allcodes - hash ref returned by &get_codes()
                   8145:    $CODE     - CODE from the current scanline
                   8146: 
                   8147:  Returns:
                   8148:    2 element list
                   8149:     - first elements is number of how closely matching the best fit is 
                   8150:       (5 means best set has 5 matching characters)
                   8151:     - second element is an arrary ref containing the set of valid CODEs
                   8152:       that best fit the passed in CODE
                   8153: 
1.423     albertel 8154: =cut
                   8155: 
1.194     albertel 8156: sub scantron_get_closely_matching_CODEs {
                   8157:     my ($allcodes,$CODE)=@_;
                   8158:     my @CODEs;
                   8159:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8160: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8161:     }
                   8162: 
                   8163:     return ($#CODEs,$CODEs[-1]);
                   8164: }
                   8165: 
1.423     albertel 8166: =pod
                   8167: 
                   8168: =item get_codes
                   8169: 
1.424     albertel 8170:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8171:    set of remembered CODEs.
                   8172: 
                   8173:  Arguments:
                   8174:   $old_name - name of the set of remembered CODEs
                   8175:   $cdom     - domain of the course
                   8176:   $cnum     - internal course name
                   8177: 
                   8178:  Returns:
                   8179:   %allcodes - keys are the valid CODEs, values are all 1
                   8180: 
1.423     albertel 8181: =cut
                   8182: 
1.194     albertel 8183: sub get_codes {
1.280     foxr     8184:     my ($old_name, $cdom, $cnum) = @_;
                   8185:     if (!$old_name) {
                   8186: 	$old_name=$env{'form.scantron_CODElist'};
                   8187:     }
                   8188:     if (!$cdom) {
                   8189: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8190:     }
                   8191:     if (!$cnum) {
                   8192: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8193:     }
1.278     albertel 8194:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8195: 				    $cdom,$cnum);
                   8196:     my %allcodes;
                   8197:     if ($result{"type\0$old_name"} eq 'number') {
                   8198: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8199:     } else {
                   8200: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8201:     }
1.194     albertel 8202:     return %allcodes;
                   8203: }
                   8204: 
1.423     albertel 8205: =pod
                   8206: 
                   8207: =item scantron_validate_CODE
                   8208: 
1.424     albertel 8209:    Validates all scanlines in the selected file to not have any
                   8210:    invalid or underspecified CODEs and that none of the codes are
                   8211:    duplicated if this was requested.
                   8212: 
1.423     albertel 8213: =cut
                   8214: 
1.157     albertel 8215: sub scantron_validate_CODE {
                   8216:     my ($r,$currentphase) = @_;
1.754     raeburn  8217:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8218:     if ($scantron_config{'CODElocation'} &&
                   8219: 	$scantron_config{'CODEstart'} &&
                   8220: 	$scantron_config{'CODElength'}) {
1.257     albertel 8221: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8222: 	    &FIXME_blow_up()
                   8223: 	}
                   8224:     } else {
                   8225: 	return (0,$currentphase+1);
                   8226:     }
                   8227:     
                   8228:     my %usedCODEs;
                   8229: 
1.194     albertel 8230:     my %allcodes=&get_codes();
1.186     albertel 8231: 
1.582     raeburn  8232:     my $nav_error;
1.649     raeburn  8233:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8234:     if ($nav_error) {
                   8235:         $r->print(&navmap_errormsg());
                   8236:         return(1,$currentphase);
                   8237:     }
1.447     foxr     8238: 
1.186     albertel 8239:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8240:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8241: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8242: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8243: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8244: 						 $scan_data);
                   8245: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8246: 	my $error=0;
1.224     albertel 8247: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8248: 	    &scantron_get_correction($r,$i,$scan_record,
                   8249: 				     \%scantron_config,
                   8250: 				     $line,'incorrectCODE',\%allcodes);
                   8251: 	    return(1,$currentphase);
                   8252: 	}
1.221     albertel 8253: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8254: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8255: 	    &scantron_get_correction($r,$i,$scan_record,
                   8256: 				     \%scantron_config,
1.194     albertel 8257: 				     $line,'incorrectCODE',\%allcodes);
                   8258: 	    return(1,$currentphase);
1.186     albertel 8259: 	}
1.214     albertel 8260: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8261: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8262: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8263: 	    &scantron_get_correction($r,$i,$scan_record,
                   8264: 				     \%scantron_config,
1.194     albertel 8265: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8266: 	    return(1,$currentphase);
1.186     albertel 8267: 	}
1.524     raeburn  8268: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8269:     }
1.157     albertel 8270:     return (0,$currentphase+1);
                   8271: }
                   8272: 
1.423     albertel 8273: =pod
                   8274: 
                   8275: =item scantron_validate_doublebubble
                   8276: 
1.424     albertel 8277:    Validates all scanlines in the selected file to not have any
                   8278:    bubble lines with multiple bubbles marked.
                   8279: 
1.423     albertel 8280: =cut
                   8281: 
1.157     albertel 8282: sub scantron_validate_doublebubble {
                   8283:     my ($r,$currentphase) = @_;
                   8284:     #get student info
                   8285:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8286:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8287:     my (undef,undef,$sequence)=
                   8288:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8289: 
                   8290:     #get scantron line setup
1.754     raeburn  8291:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8292:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8293: 
                   8294:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8295:     unless (ref($navmap)) {
                   8296:         $r->print(&navmap_errormsg());
                   8297:         return(1,$currentphase);
                   8298:     }
                   8299:     my $map=$navmap->getResourceByUrl($sequence);
                   8300:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8301:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8302:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8303:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8304: 
1.583     raeburn  8305:     my $nav_error;
1.691     raeburn  8306:     if (ref($map)) {
                   8307:         $randomorder = $map->randomorder();
                   8308:         $randompick = $map->randompick();
                   8309:         if ($randomorder || $randompick) {
                   8310:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8311:             if ($nav_error) {
                   8312:                 $r->print(&navmap_errormsg());
                   8313:                 return(1,$currentphase);
                   8314:             }
                   8315:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8316:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8317:         }
                   8318:     } else {
                   8319:         $r->print(&navmap_errormsg());
                   8320:         return(1,$currentphase);
                   8321:     }
                   8322: 
1.649     raeburn  8323:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8324:     if ($nav_error) {
                   8325:         $r->print(&navmap_errormsg());
                   8326:         return(1,$currentphase);
                   8327:     }
1.447     foxr     8328: 
1.157     albertel 8329:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8330: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8331: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8332: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8333: 						 $scan_data,undef,\%idmap,$randomorder,
                   8334:                                                  $randompick,$sequence,\@master_seq,
                   8335:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8336:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8337: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8338: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8339: 				 'doublebubble',
1.691     raeburn  8340: 				 $$scan_record{'scantron.doubleerror'},
                   8341:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8342:     	return (1,$currentphase);
                   8343:     }
                   8344:     return (0,$currentphase+1);
                   8345: }
                   8346: 
1.423     albertel 8347: 
1.503     raeburn  8348: sub scantron_get_maxbubble {
1.649     raeburn  8349:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8350:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8351: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8352: 	&restore_bubble_lines();
1.257     albertel 8353: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8354:     }
1.330     albertel 8355: 
1.447     foxr     8356:     my (undef, undef, $sequence) =
1.257     albertel 8357: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8358: 
1.447     foxr     8359:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8360:     unless (ref($navmap)) {
                   8361:         if (ref($nav_error)) {
                   8362:             $$nav_error = 1;
                   8363:         }
1.591     raeburn  8364:         return;
1.582     raeburn  8365:     }
1.191     albertel 8366:     my $map=$navmap->getResourceByUrl($sequence);
                   8367:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8368:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8369: 
                   8370:     &Apache::lonxml::clear_problem_counter();
                   8371: 
1.557     raeburn  8372:     my $uname       = $env{'user.name'};
                   8373:     my $udom        = $env{'user.domain'};
1.435     foxr     8374:     my $cid         = $env{'request.course.id'};
                   8375:     my $total_lines = 0;
                   8376:     %bubble_lines_per_response = ();
1.447     foxr     8377:     %first_bubble_line         = ();
1.503     raeburn  8378:     %subdivided_bubble_lines   = ();
                   8379:     %responsetype_per_response = ();
1.691     raeburn  8380:     %masterseq_id_responsenum  = ();
1.554     raeburn  8381: 
1.447     foxr     8382:     my $response_number = 0;
                   8383:     my $bubble_line     = 0;
1.191     albertel 8384:     foreach my $resource (@resources) {
1.691     raeburn  8385:         my $resid = $resource->id(); 
1.672     raeburn  8386:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8387:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8388:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8389: 	    foreach my $part_id (@{$parts}) {
                   8390:                 my $lines;
                   8391: 
                   8392: 	        # TODO - make this a persistent hash not an array.
                   8393: 
                   8394:                 # optionresponse, matchresponse and rankresponse type items 
                   8395:                 # render as separate sub-questions in exam mode.
                   8396:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8397:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8398:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8399:                     my ($numbub,$numshown);
                   8400:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8401:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8402:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8403:                         }
                   8404:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8405:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8406:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8407:                         }
                   8408:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8409:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8410:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8411:                         }
                   8412:                     }
                   8413:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8414:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8415:                     }
1.649     raeburn  8416:                     my $bubbles_per_row =
                   8417:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8418:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8419:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8420:                         $inner_bubble_lines++;
                   8421:                     }
                   8422:                     for (my $i=0; $i<$numshown; $i++) {
                   8423:                         $subdivided_bubble_lines{$response_number} .= 
                   8424:                             $inner_bubble_lines.',';
                   8425:                     }
                   8426:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8427:                     $lines = $numshown * $inner_bubble_lines;
                   8428:                 } else {
                   8429:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8430:                 }
1.542     raeburn  8431: 
                   8432:                 $first_bubble_line{$response_number} = $bubble_line;
                   8433: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8434:                 $responsetype_per_response{$response_number} = 
                   8435:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8436:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8437: 	        $response_number++;
                   8438: 
                   8439: 	        $bubble_line +=  $lines;
                   8440: 	        $total_lines +=  $lines;
                   8441: 	    }
                   8442:         }
                   8443:     }
1.552     raeburn  8444:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8445: 
                   8446:     &save_bubble_lines();
                   8447:     $env{'form.scantron_maxbubble'} =
                   8448: 	$total_lines;
                   8449:     return $env{'form.scantron_maxbubble'};
                   8450: }
1.523     raeburn  8451: 
1.649     raeburn  8452: sub bubblesheet_bubbles_per_row {
                   8453:     my ($scantron_config) = @_;
                   8454:     my $bubbles_per_row;
                   8455:     if (ref($scantron_config) eq 'HASH') {
                   8456:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8457:     }
                   8458:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8459:         $bubbles_per_row = 10;
                   8460:     }
                   8461:     return $bubbles_per_row;
                   8462: }
                   8463: 
1.157     albertel 8464: sub scantron_validate_missingbubbles {
                   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: 
                   8482:     my $map=$navmap->getResourceByUrl($sequence);
                   8483:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8484:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8485:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8486:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8487: 
1.582     raeburn  8488:     my $nav_error;
1.691     raeburn  8489:     if (ref($map)) {
                   8490:         $randomorder = $map->randomorder();
                   8491:         $randompick = $map->randompick();
                   8492:         if ($randomorder || $randompick) {
                   8493:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8494:             if ($nav_error) {
                   8495:                 $r->print(&navmap_errormsg());
                   8496:                 return(1,$currentphase);
                   8497:             }
                   8498:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8499:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8500:         }
                   8501:     } else {
                   8502:         $r->print(&navmap_errormsg());
                   8503:         return(1,$currentphase);
                   8504:     }
                   8505: 
                   8506: 
1.649     raeburn  8507:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8508:     if ($nav_error) {
1.691     raeburn  8509:         $r->print(&navmap_errormsg());
1.693     raeburn  8510:         return(1,$currentphase);
1.582     raeburn  8511:     }
1.691     raeburn  8512: 
1.157     albertel 8513:     if (!$max_bubble) { $max_bubble=2**31; }
                   8514:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8515: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8516: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8517: 	my $scan_record =
                   8518:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8519: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8520:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8521:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8522: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8523: 	my @to_correct;
1.470     foxr     8524: 	
                   8525: 	# Probably here's where the error is...
                   8526: 
1.157     albertel 8527: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8528:             my $lastbubble;
                   8529:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8530:                my $question = $1;
                   8531:                my $subquestion = $2;
1.691     raeburn  8532:                my ($first,$responsenum);
                   8533:                if ($randomorder || $randompick) {
                   8534:                    $responsenum = $respnumlookup{$question-1};
                   8535:                    $first = $startline{$question-1};
                   8536:                } else {
                   8537:                    $responsenum = $question-1; 
                   8538:                    $first = $first_bubble_line{$responsenum};
                   8539:                }
                   8540:                if (!defined($first)) { next; }
                   8541:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8542:                my $subcount = 1;
                   8543:                while ($subcount<$subquestion) {
                   8544:                    $first += $subans[$subcount-1];
                   8545:                    $subcount ++;
                   8546:                }
                   8547:                my $count = $subans[$subquestion-1];
                   8548:                $lastbubble = $first + $count;
                   8549:             } else {
1.691     raeburn  8550:                my ($first,$responsenum);
                   8551:                if ($randomorder || $randompick) {
                   8552:                    $responsenum = $respnumlookup{$missing-1};
                   8553:                    $first = $startline{$missing-1};
                   8554:                } else {
                   8555:                    $responsenum = $missing-1;
                   8556:                    $first = $first_bubble_line{$responsenum};
                   8557:                }
                   8558:                if (!defined($first)) { next; }
                   8559:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8560:             }
                   8561:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8562: 	    push(@to_correct,$missing);
                   8563: 	}
                   8564: 	if (@to_correct) {
                   8565: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8566: 				     $line,'missingbubble',\@to_correct,
                   8567:                                      $randomorder,$randompick,\%respnumlookup,
                   8568:                                      \%startline);
1.157     albertel 8569: 	    return (1,$currentphase);
                   8570: 	}
                   8571: 
                   8572:     }
                   8573:     return (0,$currentphase+1);
                   8574: }
                   8575: 
1.663     raeburn  8576: sub hand_bubble_option {
                   8577:     my (undef, undef, $sequence) =
                   8578:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8579:     return if ($sequence eq '');
                   8580:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8581:     unless (ref($navmap)) {
                   8582:         return;
                   8583:     }
                   8584:     my $needs_hand_bubbles;
                   8585:     my $map=$navmap->getResourceByUrl($sequence);
                   8586:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8587:     foreach my $res (@resources) {
                   8588:         if (ref($res)) {
                   8589:             if ($res->is_problem()) {
                   8590:                 my $partlist = $res->parts();
                   8591:                 foreach my $part (@{ $partlist }) {
                   8592:                     my @types = $res->responseType($part);
                   8593:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8594:                         $needs_hand_bubbles = 1;
                   8595:                         last;
                   8596:                     }
                   8597:                 }
                   8598:             }
                   8599:         }
                   8600:     }
                   8601:     if ($needs_hand_bubbles) {
1.754     raeburn  8602:         my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.663     raeburn  8603:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8604:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8605:                &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 />').
                   8606:                '<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  8607:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8608:     }
                   8609:     return;
                   8610: }
1.423     albertel 8611: 
1.82      albertel 8612: sub scantron_process_students {
1.608     www      8613:     my ($r,$symb) = @_;
1.513     foxr     8614: 
1.257     albertel 8615:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8616:     if (!$symb) {
                   8617: 	return '';
                   8618:     }
1.324     albertel 8619:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8620: 
1.754     raeburn  8621:     my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8622:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8623:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8624:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8625:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8626:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8627:     unless (ref($navmap)) {
                   8628:         $r->print(&navmap_errormsg());
                   8629:         return '';
1.691     raeburn  8630:     }
1.83      albertel 8631:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8632:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8633:         %grader_randomlists_by_symb);
1.677     raeburn  8634:     if (ref($map)) {
                   8635:         $randomorder = $map->randomorder();
1.689     raeburn  8636:         $randompick = $map->randompick();
1.691     raeburn  8637:     } else {
                   8638:         $r->print(&navmap_errormsg());
                   8639:         return '';
1.677     raeburn  8640:     }
1.691     raeburn  8641:     my $nav_error;
1.83      albertel 8642:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8643:     if ($randomorder || $randompick) {
                   8644:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8645:         if ($nav_error) {
                   8646:             $r->print(&navmap_errormsg());
                   8647:             return '';
                   8648:         }
                   8649:     }
1.557     raeburn  8650:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8651:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8652: 
1.554     raeburn  8653:     my ($uname,$udom);
1.82      albertel 8654:     my $result= <<SCANTRONFORM;
1.81      albertel 8655: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8656:   <input type="hidden" name="command" value="scantron_configphase" />
                   8657:   $default_form_data
                   8658: SCANTRONFORM
1.82      albertel 8659:     $r->print($result);
                   8660: 
                   8661:     my @delayqueue;
1.542     raeburn  8662:     my (%completedstudents,%scandata);
1.140     albertel 8663:     
1.520     www      8664:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8665:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8666:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8667:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8668:     $r->print('<br />');
1.140     albertel 8669:     my $start=&Time::HiRes::time();
1.158     albertel 8670:     my $i=-1;
1.542     raeburn  8671:     my $started;
1.447     foxr     8672: 
1.649     raeburn  8673:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8674:     if ($nav_error) {
                   8675:         $r->print(&navmap_errormsg());
                   8676:         return '';
                   8677:     }
                   8678: 
1.513     foxr     8679:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8680:     # the user and return.
                   8681: 
                   8682:     if ($ssi_error) {
                   8683: 	$r->print("</form>");
                   8684: 	&ssi_print_error($r);
1.520     www      8685:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8686: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8687:     }
1.447     foxr     8688: 
1.755     raeburn  8689:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.542     raeburn  8690:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8691:     my %orderedforcode;
1.542     raeburn  8692: 
1.157     albertel 8693:     while ($i<$scanlines->{'count'}) {
                   8694:  	($uname,$udom)=('','');
                   8695:  	$i++;
1.200     albertel 8696:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8697:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8698: 	if ($started) {
1.667     www      8699: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8700: 	}
                   8701: 	$started=1;
1.691     raeburn  8702:         my %respnumlookup = ();
                   8703:         my %startline = ();
                   8704:         my $total;
1.157     albertel 8705:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8706:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8707:                                                  $randompick,$sequence,\@master_seq,
                   8708:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8709:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8710:                                                  \$total);
1.157     albertel 8711:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8712:  					      \%idmap,$i)) {
                   8713:   	    &scantron_add_delay(\@delayqueue,$line,
                   8714:  				'Unable to find a student that matches',1);
                   8715:  	    next;
                   8716:   	}
                   8717:  	if (exists $completedstudents{$uname}) {
                   8718:  	    &scantron_add_delay(\@delayqueue,$line,
                   8719:  				'Student '.$uname.' has multiple sheets',2);
                   8720:  	    next;
                   8721:  	}
1.677     raeburn  8722:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8723:         my $user = $uname.':'.$usec;
1.157     albertel 8724:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8725: 
1.677     raeburn  8726:         my $scancode;
                   8727:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8728:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8729:             $scancode = $scan_record->{'scantron.CODE'};
                   8730:         } else {
                   8731:             $scancode = '';
                   8732:         }
                   8733: 
                   8734:         my @mapresources = @resources;
1.689     raeburn  8735:         if ($randomorder || $randompick) {
1.678     raeburn  8736:             @mapresources = 
1.691     raeburn  8737:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8738:                              \%orderedforcode);
1.677     raeburn  8739:         }
1.586     raeburn  8740:         my (%partids_by_symb,$res_error);
1.677     raeburn  8741:         foreach my $resource (@mapresources) {
1.586     raeburn  8742:             my $ressymb;
                   8743:             if (ref($resource)) {
                   8744:                 $ressymb = $resource->symb();
                   8745:             } else {
                   8746:                 $res_error = 1;
                   8747:                 last;
                   8748:             }
1.557     raeburn  8749:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8750:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  8751:                 my $currcode;
                   8752:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   8753:                     $currcode = $scancode;
                   8754:                 }
1.557     raeburn  8755:                 my ($analysis,$parts) =
1.672     raeburn  8756:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
1.741     raeburn  8757:                                               $uname,$udom,undef,$bubbles_per_row,
                   8758:                                               $currcode);
1.557     raeburn  8759:                 $partids_by_symb{$ressymb} = $parts;
                   8760:             } else {
                   8761:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8762:             }
1.554     raeburn  8763:         }
                   8764: 
1.586     raeburn  8765:         if ($res_error) {
                   8766:             &scantron_add_delay(\@delayqueue,$line,
                   8767:                                 'An error occurred while grading student '.$uname,2);
                   8768:             next;
                   8769:         }
                   8770: 
1.330     albertel 8771: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8772:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8773: 
                   8774: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8775: 	    &scantron_putfile($scanlines,$scan_data);
                   8776: 	}
1.161     albertel 8777: 	
1.542     raeburn  8778:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8779:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8780:                                    $bubbles_per_row,$randomorder,$randompick,
                   8781:                                    \%respnumlookup,\%startline) 
                   8782:             eq 'ssi_error') {
1.542     raeburn  8783:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8784:             $r->print("</form>");
                   8785:             &ssi_print_error($r);
                   8786:             &Apache::lonnet::remove_lock($lock);
                   8787:             return '';      # Why return ''?  Beats me.
                   8788:         }
1.513     foxr     8789: 
1.692     raeburn  8790:         if (($scancode) && ($randomorder || $randompick)) {
                   8791:             my $parmresult =
                   8792:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8793:                                                        '0_examcode',2,$scancode,
                   8794:                                                        'string_examcode',$uname,
                   8795:                                                        $udom);
                   8796:         }
1.140     albertel 8797: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8798:         if ($env{'form.verifyrecord'}) {
                   8799:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8800:             if ($randompick) {
                   8801:                 if ($total) {
                   8802:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8803:                 }
                   8804:             }
                   8805: 
1.542     raeburn  8806:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8807:             chomp($studentdata);
                   8808:             $studentdata =~ s/\r$//;
                   8809:             my $studentrecord = '';
                   8810:             my $counter = -1;
1.677     raeburn  8811:             foreach my $resource (@mapresources) {
1.554     raeburn  8812:                 my $ressymb = $resource->symb();
1.542     raeburn  8813:                 ($counter,my $recording) =
                   8814:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8815:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8816:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8817:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8818:                 $studentrecord .= $recording;
                   8819:             }
                   8820:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8821:                 &Apache::lonxml::clear_problem_counter();
                   8822:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8823:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8824:                                            $bubbles_per_row,$randomorder,$randompick,
                   8825:                                            \%respnumlookup,\%startline) 
                   8826:                     eq 'ssi_error') {
1.554     raeburn  8827:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8828:                     $r->print("</form>");
                   8829:                     &ssi_print_error($r);
                   8830:                     &Apache::lonnet::remove_lock($lock);
                   8831:                     delete($completedstudents{$uname});
                   8832:                     return '';
                   8833:                 }
1.542     raeburn  8834:                 $counter = -1;
                   8835:                 $studentrecord = '';
1.677     raeburn  8836:                 foreach my $resource (@mapresources) {
1.554     raeburn  8837:                     my $ressymb = $resource->symb();
1.542     raeburn  8838:                     ($counter,my $recording) =
                   8839:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8840:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8841:                                                  \%scantron_config,\%lettdig,$numletts,
                   8842:                                                  $randomorder,$randompick,\%respnumlookup,
                   8843:                                                  \%startline);
1.542     raeburn  8844:                     $studentrecord .= $recording;
                   8845:                 }
                   8846:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8847:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8848:                     if ($scancode eq '') {
1.658     bisitz   8849:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8850:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8851:                     } else {
1.658     bisitz   8852:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8853:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8854:                     }
                   8855:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8856:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8857:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8858:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8859:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8860:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8861:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8862:                               &Apache::loncommon::end_data_table_row().
                   8863:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8864:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8865:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8866:                               &Apache::loncommon::end_data_table_row().
                   8867:                               &Apache::loncommon::end_data_table().'</p>');
                   8868:                 } else {
                   8869:                     $r->print('<br /><span class="LC_warning">'.
                   8870:                              &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 />'.
                   8871:                              &mt("As a consequence, this user's submission history records two tries.").
                   8872:                                  '</span><br />');
                   8873:                 }
                   8874:             }
                   8875:         }
1.543     raeburn  8876:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8877:     } continue {
1.330     albertel 8878: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8879: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8880:     }
1.140     albertel 8881:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8882:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8883: #    my $lasttime = &Time::HiRes::time()-$start;
                   8884: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8885: 
1.200     albertel 8886:     $r->print("</form>");
1.157     albertel 8887:     return '';
1.75      albertel 8888: }
1.157     albertel 8889: 
1.557     raeburn  8890: sub graders_resources_pass {
1.649     raeburn  8891:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8892:         $bubbles_per_row) = @_;
1.557     raeburn  8893:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8894:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8895:         foreach my $resource (@{$resources}) {
                   8896:             my $ressymb = $resource->symb();
                   8897:             my ($analysis,$parts) =
                   8898:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8899:                                           $env{'user.name'},$env{'user.domain'},
                   8900:                                           1,$bubbles_per_row);
1.557     raeburn  8901:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8902:             if (ref($analysis) eq 'HASH') {
                   8903:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8904:                     $grader_randomlists_by_symb->{$ressymb} =
                   8905:                         $analysis->{'parts_withrandomlist'};
                   8906:                 }
                   8907:             }
                   8908:         }
                   8909:     }
                   8910:     return;
                   8911: }
                   8912: 
1.678     raeburn  8913: =pod
                   8914: 
                   8915: =item users_order
                   8916: 
                   8917:   Returns array of resources in current map, ordered based on either CODE,
                   8918:   if this is a CODEd exam, or based on student's identity if this is a 
                   8919:   "NAMEd" exam.
                   8920: 
1.691     raeburn  8921:   Should be used when randomorder and/or randompick applied when the 
                   8922:   corresponding exam was printed, prior to students completing bubblesheets 
                   8923:   for the version of the exam the student received.
1.678     raeburn  8924: 
                   8925: =cut
                   8926: 
                   8927: sub users_order  {
1.691     raeburn  8928:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8929:     my @mapresources;
1.691     raeburn  8930:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8931:         return @mapresources;
1.691     raeburn  8932:     }
                   8933:     if ($scancode) {
                   8934:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8935:             @mapresources = @{$orderedforcode->{$scancode}};
                   8936:         } else {
                   8937:             $env{'form.CODE'} = $scancode;
                   8938:             my $actual_seq =
                   8939:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8940:                                                                $master_seq,
                   8941:                                                                $user,$scancode,1);
                   8942:             if (ref($actual_seq) eq 'ARRAY') {
                   8943:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8944:                 if (ref($orderedforcode) eq 'HASH') {
                   8945:                     if (@mapresources > 0) { 
                   8946:                         $orderedforcode->{$scancode} = \@mapresources;
                   8947:                     }
                   8948:                 }
                   8949:             }
                   8950:             delete($env{'form.CODE'});
1.678     raeburn  8951:         }
                   8952:     } else {
                   8953:         my $actual_seq =
                   8954:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8955:                                                            $master_seq,
1.688     raeburn  8956:                                                            $user,undef,1);
1.678     raeburn  8957:         if (ref($actual_seq) eq 'ARRAY') {
                   8958:             @mapresources = 
                   8959:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8960:         }
1.691     raeburn  8961:     }
                   8962:     return @mapresources;
1.678     raeburn  8963: }
                   8964: 
1.542     raeburn  8965: sub grade_student_bubbles {
1.691     raeburn  8966:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8967:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8968:     my $uselookup = 0;
                   8969:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8970:         (ref($startline) eq 'HASH')) {
                   8971:         $uselookup = 1;
                   8972:     }
                   8973: 
1.554     raeburn  8974:     if (ref($resources) eq 'ARRAY') {
                   8975:         my $count = 0;
                   8976:         foreach my $resource (@{$resources}) {
                   8977:             my $ressymb = $resource->symb();
                   8978:             my %form = ('submitted'      => 'scantron',
                   8979:                         'grade_target'   => 'grade',
                   8980:                         'grade_username' => $uname,
                   8981:                         'grade_domain'   => $udom,
                   8982:                         'grade_courseid' => $env{'request.course.id'},
                   8983:                         'grade_symb'     => $ressymb,
                   8984:                         'CODE'           => $scancode
                   8985:                        );
1.649     raeburn  8986:             if ($bubbles_per_row ne '') {
                   8987:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8988:             }
1.663     raeburn  8989:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8990:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8991:             }
1.554     raeburn  8992:             if (ref($parts) eq 'HASH') {
                   8993:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8994:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8995:                         if ($uselookup) {
                   8996:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8997:                         } else {
                   8998:                             $form{'scantron_questnum_start.'.$part} =
                   8999:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9000:                         }
1.554     raeburn  9001:                         $count++;
                   9002:                     }
                   9003:                 }
                   9004:             }
                   9005:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9006:             return 'ssi_error' if ($ssi_error);
                   9007:             last if (&Apache::loncommon::connection_aborted($r));
                   9008:         }
1.542     raeburn  9009:     }
                   9010:     return;
                   9011: }
                   9012: 
1.157     albertel 9013: sub scantron_upload_scantron_data {
1.608     www      9014:     my ($r,$symb)=@_;
1.565     raeburn  9015:     my $dom = $env{'request.role.domain'};
1.754     raeburn  9016:     my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
1.565     raeburn  9017:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9018:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9019:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9020: 							  'domainid',
1.565     raeburn  9021: 							  'coursename',$dom);
                   9022:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   9023:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      9024:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9025:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.736     damieng  9026:     &js_escape(\$nofile_alert);
1.579     raeburn  9027:     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  9028:     &js_escape(\$nocourseid_alert);
1.597     wenzelju 9029:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 9030:     function checkUpload(formname) {
                   9031: 	if (formname.upfile.value == "") {
1.579     raeburn  9032: 	    alert("'.$nofile_alert.'");
1.157     albertel 9033: 	    return false;
                   9034: 	}
1.565     raeburn  9035:         if (formname.courseid.value == "") {
1.579     raeburn  9036:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9037:             return false;
                   9038:         }
1.157     albertel 9039: 	formname.submit();
                   9040:     }
1.565     raeburn  9041: 
                   9042:     function ToSyllabus() {
                   9043:         var cdom = '."'$dom'".';
                   9044:         var cnum = document.rules.courseid.value;
                   9045:         if (cdom == "" || cdom == null) {
                   9046:             return;
                   9047:         }
                   9048:         if (cnum == "" || cnum == null) {
                   9049:            return;
                   9050:         }
                   9051:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9052:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9053:         return;
                   9054:     }
                   9055: 
1.754     raeburn  9056:     '.$formatjs.'
1.597     wenzelju 9057: '));
                   9058:     $r->print('
1.648     bisitz   9059: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9060: 
1.492     albertel 9061: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9062: '.$default_form_data.
                   9063:   &Apache::lonhtmlcommon::start_pick_box().
                   9064:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9065:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9066:   &Apache::lonhtmlcommon::row_closure().
                   9067:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9068:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9069:   &Apache::lonhtmlcommon::row_closure().
                   9070:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9071:   '<input name="domainid" type="hidden" />'.$domdesc.
1.754     raeburn  9072:   &Apache::lonhtmlcommon::row_closure());
                   9073:     if ($formatoptions) {
                   9074:         $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
                   9075:                   &Apache::lonhtmlcommon::row_closure());
                   9076:     }
                   9077:     $r->print(
1.565     raeburn  9078:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9079:   '<input type="file" name="upfile" size="50" />'.
                   9080:   &Apache::lonhtmlcommon::row_closure(1).
                   9081:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9082: 
1.492     albertel 9083: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9084: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9085: </form>
1.492     albertel 9086: ');
1.157     albertel 9087:     return '';
                   9088: }
                   9089: 
1.754     raeburn  9090: sub scantron_upload_dataformat {
                   9091:     my ($dom) = @_;
                   9092:     my ($formatoptions,$formattitle,$formatjs);
                   9093:     $formatjs = <<'END';
                   9094: function toggleScantab(form) {
                   9095:    return;
                   9096: }
                   9097: END
                   9098:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
                   9099:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9100:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9101:             if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
                   9102:                 if (($domconfig{'scantron'}{'config'}{'dat'}) &&
                   9103:                     (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
1.756     raeburn  9104:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {  
                   9105:                         if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
                   9106:                             my ($onclick,$formatextra,$singleline);
                   9107:                             my @lines = &Apache::lonnet::get_scantronformat_file();
                   9108:                             my $count = 0;
                   9109:                             foreach my $line (@lines) {
                   9110:                                 next if ($line =~ /^#/);
                   9111:                                 $singleline = $line;
                   9112:                                 $count ++;
                   9113:                             }
                   9114:                             if ($count > 1) {
                   9115:                                 $formatextra = '<div style="display:none" id="bubbletype">'.
1.757     raeburn  9116:                                                '<span class="LC_nobreak">'.
                   9117:                                                &mt('Bubblesheet type:').'&nbsp;'.
                   9118:                                                &scantron_scantab().'</span></div>';
1.756     raeburn  9119:                                 $onclick = ' onclick="toggleScantab(this.form);"';
                   9120:                                 $formatjs = <<"END";
1.754     raeburn  9121: function toggleScantab(form) {
                   9122:     var divid = 'bubbletype';
                   9123:     if (document.getElementById(divid)) {
                   9124:         var radioname = 'fileformat';
                   9125:         var num = form.elements[radioname].length;
                   9126:         if (num) {
                   9127:             for (var i=0; i<num; i++) {
                   9128:                 if (form.elements[radioname][i].checked) {
                   9129:                     var chosen = form.elements[radioname][i].value;
                   9130:                     if (chosen == 'dat') {
                   9131:                         document.getElementById(divid).style.display = 'none';
                   9132:                     } else if (chosen == 'csv') {
1.757     raeburn  9133:                         document.getElementById(divid).style.display = 'block';
1.754     raeburn  9134:                     }
                   9135:                 }
                   9136:             }
                   9137:         }
                   9138:     }
                   9139:     return;
                   9140: }
                   9141: 
                   9142: END
1.756     raeburn  9143:                             } elsif ($count == 1) {
                   9144:                                 my $formatname = (split(/:/,$singleline,2))[0];
                   9145:                                 $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
                   9146:                             }
                   9147:                             $formattitle = &mt('File format');
                   9148:                             $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
                   9149:                                              &mt('Plain Text (no delimiters)').
                   9150:                                              '</label>'.('&nbsp;'x2).
                   9151:                                              '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
                   9152:                                              &mt('Comma separated values').'</label>'.$formatextra;
1.754     raeburn  9153:                         }
                   9154:                     }
                   9155:                 }
                   9156:             } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
1.756     raeburn  9157:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9158:                     if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
1.757     raeburn  9159:                         $formattitle = &mt('Bubblesheet type');
1.756     raeburn  9160:                         $formatoptions = &scantron_scantab();
                   9161:                     }
1.754     raeburn  9162:                 }
                   9163:             }
                   9164:         }
                   9165:     }
                   9166:     return ($formatoptions,$formattitle,$formatjs);
                   9167: }
1.423     albertel 9168: 
1.157     albertel 9169: sub scantron_upload_scantron_data_save {
1.608     www      9170:     my($r,$symb)=@_;
1.182     albertel 9171:     my $doanotherupload=
                   9172: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9173: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9174: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9175: 	'</form>'."\n";
1.257     albertel 9176:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9177: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9178: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9179: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      9180: 	unless ($symb) {
1.182     albertel 9181: 	    $r->print($doanotherupload);
                   9182: 	}
1.162     albertel 9183: 	return '';
                   9184:     }
1.257     albertel 9185:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9186:     my $uploadedfile;
1.710     bisitz   9187:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 9188:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9189:         $r->print(
                   9190:             &Apache::lonhtmlcommon::confirm_success(
                   9191:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9192:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9193:     } else {
1.754     raeburn  9194:         my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
                   9195:         my $parser;
                   9196:         if (ref($domconfig{'scantron'}) eq 'HASH') {
                   9197:             if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
                   9198:                 my $is_csv;
                   9199:                 my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
                   9200:                 if (@possibles > 1) {
                   9201:                     if ($env{'form.fileformat'} eq 'csv') {
                   9202:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9203:                             if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9204:                                 if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9205:                                     $is_csv = 1;
                   9206:                                 }
1.754     raeburn  9207:                             }
                   9208:                         }
                   9209:                     }
                   9210:                 } elsif (@possibles == 1) {
                   9211:                     if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
1.756     raeburn  9212:                         if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
                   9213:                             if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
                   9214:                                 $is_csv = 1;
                   9215:                             }
1.754     raeburn  9216:                         }
                   9217:                     }
                   9218:                 }
                   9219:                 if ($is_csv) {
                   9220:                    $parser = $domconfig{'scantron'}{'config'}{'csv'};
                   9221:                 }
                   9222:             }
                   9223:         }
                   9224:         my $result =
                   9225:             &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
1.568     raeburn  9226:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   9227:         if ($result =~ m{^/uploaded/}) {
                   9228:             $r->print(
                   9229:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9230:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9231:                         (length($env{'form.upfile'})-1),
                   9232:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9233:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9234:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9235:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   9236:         } else {
                   9237:             $r->print(
                   9238:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9239:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9240:                           $result,
1.568     raeburn  9241: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9242: 	}
                   9243:     }
1.174     albertel 9244:     if ($symb) {
1.612     www      9245: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 9246:     } else {
1.182     albertel 9247: 	$r->print($doanotherupload);
1.174     albertel 9248:     }
1.157     albertel 9249:     return '';
                   9250: }
                   9251: 
1.567     raeburn  9252: sub validate_uploaded_scantron_file {
                   9253:     my ($cdom,$cname,$fname) = @_;
                   9254:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9255:     my @lines;
                   9256:     if ($scanlines ne '-1') {
                   9257:         @lines=split("\n",$scanlines,-1);
                   9258:     }
                   9259:     my $output;
                   9260:     if (@lines) {
                   9261:         my (%counts,$max_match_format);
1.710     bisitz   9262:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9263:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9264:         my %idmap = &username_to_idmap($classlist);
                   9265:         foreach my $key (keys(%idmap)) {
                   9266:             my $lckey = lc($key);
                   9267:             $idmap{$lckey} = $idmap{$key};
                   9268:         }
                   9269:         my %unique_formats;
1.754     raeburn  9270:         my @formatlines = &Apache::lonnet::get_scantronformat_file();
1.567     raeburn  9271:         foreach my $line (@formatlines) {
                   9272:             chomp($line);
                   9273:             my @config = split(/:/,$line);
                   9274:             my $idstart = $config[5];
                   9275:             my $idlength = $config[6];
                   9276:             if (($idstart ne '') && ($idlength > 0)) {
                   9277:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9278:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9279:                 } else {
                   9280:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9281:                 }
                   9282:             }
                   9283:         }
                   9284:         foreach my $key (keys(%unique_formats)) {
                   9285:             my ($idstart,$idlength) = split(':',$key);
                   9286:             %{$counts{$key}} = (
                   9287:                                'found'   => 0,
                   9288:                                'total'   => 0,
                   9289:                               );
                   9290:             foreach my $line (@lines) {
                   9291:                 next if ($line =~ /^#/);
                   9292:                 next if ($line =~ /^[\s\cz]*$/);
                   9293:                 my $id = substr($line,$idstart-1,$idlength);
                   9294:                 $id = lc($id);
                   9295:                 if (exists($idmap{$id})) {
                   9296:                     $counts{$key}{'found'} ++;
                   9297:                 }
                   9298:                 $counts{$key}{'total'} ++;
                   9299:             }
                   9300:             if ($counts{$key}{'total'}) {
                   9301:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9302:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9303:                     $max_match_pct = $percent_match;
                   9304:                     $max_match_format = $key;
1.710     bisitz   9305:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9306:                     $max_match_count = $counts{$key}{'total'};
                   9307:                 }
                   9308:             }
                   9309:         }
                   9310:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9311:             my $format_descs;
                   9312:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9313:             for (my $i=0; $i<$numwithformat; $i++) {
                   9314:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9315:                 if ($i<$numwithformat-2) {
                   9316:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9317:                 } elsif ($i==$numwithformat-2) {
                   9318:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9319:                 } elsif ($i==$numwithformat-1) {
                   9320:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9321:                 }
                   9322:             }
                   9323:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   9324:             $output .= '<br />';
                   9325:             if ($found_match_count == $max_match_count) {
                   9326:                 # 100% matching entries
                   9327:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9328:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9329:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9330:                 &mt('Comparison of student IDs in the uploaded file with'.
                   9331:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9332:                     ' in the file (for the format defined for [_3]).',
                   9333:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9334:             } else {
                   9335:                 # Not all entries matching? -> Show warning and additional info
                   9336:                 $output .=
                   9337:                     &Apache::lonhtmlcommon::confirm_success(
                   9338:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9339:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9340:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9341:                     &mt('Comparison of student IDs in the uploaded file with'.
                   9342:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9343:                         ' in the file (for the format defined for [_3]).',
                   9344:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9345:                     '<p class="LC_info">'.
                   9346:                     &mt('A low percentage of matches results from one of the following:').
                   9347:                     '</p><ul>'.
                   9348:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9349:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9350:                                '<i>'.$cdom.'</i>').'</li>'.
                   9351:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9352:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9353:                     '</ul>';
                   9354:             }
1.567     raeburn  9355:         }
                   9356:     } else {
1.710     bisitz   9357:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9358:     }
                   9359:     return $output;
                   9360: }
                   9361: 
1.202     albertel 9362: sub valid_file {
                   9363:     my ($requested_file)=@_;
                   9364:     foreach my $filename (sort(&scantron_filenames())) {
                   9365: 	if ($requested_file eq $filename) { return 1; }
                   9366:     }
                   9367:     return 0;
                   9368: }
                   9369: 
                   9370: sub scantron_download_scantron_data {
1.608     www      9371:     my ($r,$symb)=@_;
                   9372:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9373:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9374:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9375:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9376:     if (! &valid_file($file)) {
1.492     albertel 9377: 	$r->print('
1.202     albertel 9378: 	<p>
1.686     bisitz   9379: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9380:         </p>
1.492     albertel 9381: ');
1.202     albertel 9382: 	return;
                   9383:     }
                   9384:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9385:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9386:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9387:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9388:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9389:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9390:     $r->print('
1.202     albertel 9391:     <p>
1.723     raeburn  9392: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 9393: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9394:     </p>
                   9395:     <p>
1.492     albertel 9396: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9397: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9398:     </p>
                   9399:     <p>
1.492     albertel 9400: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9401: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9402:     </p>
1.492     albertel 9403: ');
1.202     albertel 9404:     return '';
                   9405: }
1.157     albertel 9406: 
1.523     raeburn  9407: sub checkscantron_results {
1.608     www      9408:     my ($r,$symb) = @_;
1.523     raeburn  9409:     if (!$symb) {return '';}
                   9410:     my $cid = $env{'request.course.id'};
1.755     raeburn  9411:     my %lettdig = &Apache::lonnet::letter_to_digits();
1.523     raeburn  9412:     my $numletts = scalar(keys(%lettdig));
                   9413:     my $cnum = $env{'course.'.$cid.'.num'};
                   9414:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9415:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9416:     my %record;
                   9417:     my %scantron_config =
1.754     raeburn  9418:         &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  9419:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9420:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9421:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9422:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9423:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9424:     unless (ref($navmap)) {
                   9425:         $r->print(&navmap_errormsg());
                   9426:         return '';
                   9427:     }
1.523     raeburn  9428:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  9429:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9430:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  9431:     if (ref($map)) { 
                   9432:         $randomorder=$map->randomorder();
1.689     raeburn  9433:         $randompick=$map->randompick();
1.677     raeburn  9434:     }
1.557     raeburn  9435:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  9436:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9437:     if ($nav_error) {
                   9438:         $r->print(&navmap_errormsg());
                   9439:         return '';
1.678     raeburn  9440:     }
1.673     raeburn  9441:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9442:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9443:     my ($uname,$udom);
1.523     raeburn  9444:     my (%scandata,%lastname,%bylast);
                   9445:     $r->print('
                   9446: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9447: 
                   9448:     my @delayqueue;
                   9449:     my %completedstudents;
                   9450: 
1.691     raeburn  9451:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      9452:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  9453:     my ($username,$domain,$started);
1.649     raeburn  9454:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9455:     if ($nav_error) {
                   9456:         $r->print(&navmap_errormsg());
                   9457:         return '';
                   9458:     }
1.523     raeburn  9459: 
1.667     www      9460:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  9461:     my $start=&Time::HiRes::time();
                   9462:     my $i=-1;
                   9463: 
                   9464:     while ($i<$scanlines->{'count'}) {
                   9465:         ($username,$domain,$uname)=('','','');
                   9466:         $i++;
                   9467:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9468:         if ($line=~/^[\s\cz]*$/) { next; }
                   9469:         if ($started) {
1.667     www      9470:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  9471:         }
                   9472:         $started=1;
                   9473:         my $scan_record=
                   9474:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9475:                                                      $scan_data);
1.693     raeburn  9476:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9477:                                               \%idmap,$i)) {
1.523     raeburn  9478:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9479:                                 'Unable to find a student that matches',1);
                   9480:             next;
                   9481:         }
                   9482:         if (exists $completedstudents{$uname}) {
                   9483:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9484:                                 'Student '.$uname.' has multiple sheets',2);
                   9485:             next;
                   9486:         }
                   9487:         my $pid = $scan_record->{'scantron.ID'};
                   9488:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9489:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9490:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9491:         my $user = $uname.':'.$usec;
1.523     raeburn  9492:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9493: 
1.678     raeburn  9494:         my $scancode;
1.677     raeburn  9495:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9496:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9497:             $scancode = $scan_record->{'scantron.CODE'};
                   9498:         } else {
                   9499:             $scancode = '';
                   9500:         }
                   9501: 
                   9502:         my @mapresources = @resources;
1.691     raeburn  9503:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9504:         my %respnumlookup=();
                   9505:         my %startline=();
1.689     raeburn  9506:         if ($randomorder || $randompick) {
1.678     raeburn  9507:             @mapresources =
1.691     raeburn  9508:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9509:                              \%orderedforcode);
                   9510:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9511:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9512:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9513:                                              \%respnumlookup,\%startline);
                   9514:             if ($randompick && $total) {
                   9515:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9516:             }
1.677     raeburn  9517:         }
1.691     raeburn  9518:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9519:         chomp($scandata{$pid});
                   9520:         $scandata{$pid} =~ s/\r$//;
                   9521: 
1.523     raeburn  9522:         my $counter = -1;
1.677     raeburn  9523:         foreach my $resource (@mapresources) {
1.557     raeburn  9524:             my $parts;
1.554     raeburn  9525:             my $ressymb = $resource->symb();
1.557     raeburn  9526:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9527:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
1.741     raeburn  9528:                 my $currcode;
                   9529:                 if (exists($grader_randomlists_by_symb{$ressymb})) {
                   9530:                     $currcode = $scancode;
                   9531:                 }
1.557     raeburn  9532:                 (my $analysis,$parts) =
1.672     raeburn  9533:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9534:                                               $username,$domain,undef,
1.741     raeburn  9535:                                               $bubbles_per_row,$currcode);
1.557     raeburn  9536:             } else {
                   9537:                 $parts = $grader_partids_by_symb{$ressymb};
                   9538:             }
1.542     raeburn  9539:             ($counter,my $recording) =
                   9540:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9541:                                          $scandata{$pid},$parts,
1.691     raeburn  9542:                                          \%scantron_config,\%lettdig,$numletts,
                   9543:                                          $randomorder,$randompick,
                   9544:                                          \%respnumlookup,\%startline);
1.542     raeburn  9545:             $record{$pid} .= $recording;
1.523     raeburn  9546:         }
                   9547:     }
                   9548:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9549:     $r->print('<br />');
                   9550:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9551:     $passed = 0;
                   9552:     $failed = 0;
                   9553:     $numstudents = 0;
                   9554:     foreach my $last (sort(keys(%bylast))) {
                   9555:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9556:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9557:                 my $showscandata = $scandata{$pid};
                   9558:                 my $showrecord = $record{$pid};
                   9559:                 $showscandata =~ s/\s/&nbsp;/g;
                   9560:                 $showrecord =~ s/\s/&nbsp;/g;
                   9561:                 if ($scandata{$pid} eq $record{$pid}) {
                   9562:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9563:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9564: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9565: '</tr>'."\n".
                   9566: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9567: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9568:                     $passed ++;
                   9569:                 } else {
                   9570:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9571:                     $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  9572: '</tr>'."\n".
                   9573: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9574: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9575: '</tr>'."\n";
                   9576:                     $failed ++;
                   9577:                 }
                   9578:                 $numstudents ++;
                   9579:             }
                   9580:         }
                   9581:     }
1.648     bisitz   9582:     $r->print(
                   9583:         '<p>'
                   9584:        .&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).',
                   9585:             '<b>',
                   9586:             $numstudents,
                   9587:             '</b>',
                   9588:             $env{'form.scantron_maxbubble'})
                   9589:        .'</p>'
                   9590:     );
1.682     raeburn  9591:     $r->print('<p>'
1.683     raeburn  9592:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9593:              .'<br />'
                   9594:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9595:              .'</p>'
                   9596:     );
1.523     raeburn  9597:     if ($passed) {
1.572     www      9598:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9599:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9600:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9601:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9602:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9603:                  $okstudents."\n".
                   9604:                  &Apache::loncommon::end_data_table().'<br />');
                   9605:     }
                   9606:     if ($failed) {
1.572     www      9607:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9608:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9609:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9610:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9611:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9612:                  $badstudents."\n".
                   9613:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9614:                  &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  9615:     }
1.614     www      9616:     $r->print('</form><br />');
1.523     raeburn  9617:     return;
                   9618: }
                   9619: 
1.542     raeburn  9620: sub verify_scantron_grading {
1.554     raeburn  9621:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9622:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9623:         $respnumlookup,$startline) = @_;
1.542     raeburn  9624:     my ($record,%expected,%startpos);
                   9625:     return ($counter,$record) if (!ref($resource));
                   9626:     return ($counter,$record) if (!$resource->is_problem());
                   9627:     my $symb = $resource->symb();
1.554     raeburn  9628:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9629:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9630:         $counter ++;
                   9631:         $expected{$part_id} = 0;
1.691     raeburn  9632:         my $respnum = $counter;
                   9633:         if ($randomorder || $randompick) {
                   9634:             $respnum = $respnumlookup->{$counter};
                   9635:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9636:         } else {
                   9637:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9638:         }
                   9639:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9640:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9641:             foreach my $item (@sub_lines) {
                   9642:                 $expected{$part_id} += $item;
                   9643:             }
                   9644:         } else {
1.691     raeburn  9645:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9646:         }
                   9647:     }
                   9648:     if ($symb) {
                   9649:         my %recorded;
                   9650:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9651:         if ($returnhash{'version'}) {
                   9652:             my %lasthash=();
                   9653:             my $version;
                   9654:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9655:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9656:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9657:                 }
                   9658:             }
                   9659:             foreach my $key (keys(%lasthash)) {
                   9660:                 if ($key =~ /\.scantron$/) {
                   9661:                     my $value = &unescape($lasthash{$key});
                   9662:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9663:                     if ($value eq '') {
                   9664:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9665:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9666:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9667:                             }
                   9668:                         }
                   9669:                     } else {
                   9670:                         my @tocheck;
                   9671:                         my @items = split(//,$value);
                   9672:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9673:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9674:                             if (@items < $expected{$part_id}) {
                   9675:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9676:                                 my @singles = split(//,$fragment);
                   9677:                                 foreach my $pos (@singles) {
                   9678:                                     if ($pos eq ' ') {
                   9679:                                         push(@tocheck,$pos);
                   9680:                                     } else {
                   9681:                                         my $next = shift(@items);
                   9682:                                         push(@tocheck,$next);
                   9683:                                     }
                   9684:                                 }
                   9685:                             } else {
                   9686:                                 @tocheck = @items;
                   9687:                             }
                   9688:                             foreach my $letter (@tocheck) {
                   9689:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9690:                                     if ($letter !~ /^[A-J]$/) {
                   9691:                                         $letter = $scantron_config->{'Qoff'};
                   9692:                                     }
                   9693:                                     $recorded{$part_id} .= $letter;
                   9694:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9695:                                     my $digit;
                   9696:                                     if ($letter !~ /^[A-J]$/) {
                   9697:                                         $digit = $scantron_config->{'Qoff'};
                   9698:                                     } else {
                   9699:                                         $digit = $lettdig->{$letter};
                   9700:                                     }
                   9701:                                     $recorded{$part_id} .= $digit;
                   9702:                                 }
                   9703:                             }
                   9704:                         } else {
                   9705:                             @tocheck = @items;
                   9706:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9707:                                 my $curr_sub = shift(@tocheck);
                   9708:                                 my $digit;
                   9709:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9710:                                     $digit = $lettdig->{$curr_sub}-1;
                   9711:                                 }
                   9712:                                 if ($curr_sub eq 'J') {
                   9713:                                     $digit += scalar($numletts);
                   9714:                                 }
                   9715:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9716:                                     if ($j == $digit) {
                   9717:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9718:                                     } else {
                   9719:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9720:                                     }
                   9721:                                 }
                   9722:                             }
                   9723:                         }
                   9724:                     }
                   9725:                 }
                   9726:             }
                   9727:         }
1.554     raeburn  9728:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9729:             if ($recorded{$part_id} eq '') {
                   9730:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9731:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9732:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9733:                     }
                   9734:                 }
                   9735:             }
                   9736:             $record .= $recorded{$part_id};
                   9737:         }
                   9738:     }
                   9739:     return ($counter,$record);
                   9740: }
                   9741: 
1.423     albertel 9742: 
1.75      albertel 9743: #-------- end of section for handling grading scantron forms -------
                   9744: #
                   9745: #-------------------------------------------------------------------
                   9746: 
1.72      ng       9747: #-------------------------- Menu interface -------------------------
                   9748: #
1.614     www      9749: #--- Href with symb and command ---
                   9750: 
                   9751: sub href_symb_cmd {
                   9752:     my ($symb,$cmd)=@_;
1.669     raeburn  9753:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9754: }
                   9755: 
1.443     banghart 9756: sub grading_menu {
1.608     www      9757:     my ($request,$symb) = @_;
1.443     banghart 9758:     if (!$symb) {return '';}
                   9759: 
                   9760:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9761:                   'command'=>'individual');
1.538     schulted 9762:     
1.598     www      9763:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9764: 
                   9765:     $fields{'command'}='ungraded';
                   9766:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9767: 
                   9768:     $fields{'command'}='table';
                   9769:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9770: 
                   9771:     $fields{'command'}='all_for_one';
                   9772:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9773: 
1.621     www      9774:     $fields{'command'}='downloadfilesselect';
                   9775:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9776: 
1.443     banghart 9777:     $fields{'command'} = 'csvform';
1.538     schulted 9778:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9779:     
1.443     banghart 9780:     $fields{'command'} = 'processclicker';
1.538     schulted 9781:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9782:     
1.443     banghart 9783:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9784:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9785: 
                   9786:     $fields{'command'} = 'initialverifyreceipt';
                   9787:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9788:     
1.598     www      9789:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9790:             items =>[
1.598     www      9791:                         {	linktext => 'Select individual students to grade',
                   9792:                     		url => $url1a,
1.538     schulted 9793:                     		permission => 'F',
1.636     wenzelju 9794:                     		icon => 'grade_students.png',
1.598     www      9795:                     		linktitle => 'Grade current resource for a selection of students.'
                   9796:                         }, 
                   9797:                         {       linktext => 'Grade ungraded submissions.',
                   9798:                                 url => $url1b,
                   9799:                                 permission => 'F',
1.636     wenzelju 9800:                                 icon => 'ungrade_sub.png',
1.598     www      9801:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9802:                         },
1.598     www      9803: 
                   9804:                         {       linktext => 'Grading table',
                   9805:                                 url => $url1c,
                   9806:                                 permission => 'F',
1.636     wenzelju 9807:                                 icon => 'grading_table.png',
1.598     www      9808:                                 linktitle => 'Grade current resource for all students.'
                   9809:                         },
1.615     www      9810:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9811:                                 url => $url1d,
                   9812:                                 permission => 'F',
1.636     wenzelju 9813:                                 icon => 'grade_PageFolder.png',
1.598     www      9814:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9815:                         },
                   9816:                         {       linktext => 'Download submissions',
                   9817:                                 url => $url1e,
                   9818:                                 permission => 'F',
1.636     wenzelju 9819:                                 icon => 'download_sub.png',
1.621     www      9820:                                 linktitle => 'Download all students submissions.'
1.598     www      9821:                         }]},
                   9822:                          { categorytitle=>'Automated Grading',
                   9823:                items =>[
                   9824: 
1.538     schulted 9825:                 	    {	linktext => 'Upload Scores',
                   9826:                     		url => $url2,
                   9827:                     		permission => 'F',
                   9828:                     		icon => 'uploadscores.png',
                   9829:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9830:                 	    },
                   9831:                 	    {	linktext => 'Process Clicker',
                   9832:                     		url => $url3,
                   9833:                     		permission => 'F',
                   9834:                     		icon => 'addClickerInfoFile.png',
                   9835:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9836:                 	    },
1.587     raeburn  9837:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9838:                     		url => $url4,
                   9839:                     		permission => 'F',
1.636     wenzelju 9840:                     		icon => 'bubblesheet.png',
1.648     bisitz   9841:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9842:                 	    },
1.616     www      9843:                             {   linktext => 'Verify Receipt Number',
1.602     www      9844:                                 url => $url5,
                   9845:                                 permission => 'F',
1.636     wenzelju 9846:                                 icon => 'receipt_number.png',
1.602     www      9847:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9848:                             }
                   9849: 
1.538     schulted 9850:                     ]
                   9851:             });
                   9852: 
1.443     banghart 9853:     # Create the menu
                   9854:     my $Str;
1.445     banghart 9855:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9856:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9857:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9858: 
1.602     www      9859:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9860:     return $Str;    
                   9861: }
                   9862: 
1.598     www      9863: 
                   9864: sub ungraded {
                   9865:     my ($request)=@_;
                   9866:     &submit_options($request);
                   9867: }
                   9868: 
1.599     www      9869: sub submit_options_sequence {
1.608     www      9870:     my ($request,$symb) = @_;
1.599     www      9871:     if (!$symb) {return '';}
1.600     www      9872:     &commonJSfunctions($request);
                   9873:     my $result;
1.599     www      9874: 
1.600     www      9875:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9876:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9877:     $result.=&selectfield(0).
1.601     www      9878:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9879:             <div>
                   9880:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9881:             </div>
                   9882:         </div>
                   9883:   </form>';
                   9884:     return $result;
                   9885: }
                   9886: 
                   9887: sub submit_options_table {
1.608     www      9888:     my ($request,$symb) = @_;
1.600     www      9889:     if (!$symb) {return '';}
1.599     www      9890:     &commonJSfunctions($request);
1.746     raeburn  9891:     my $is_tool = ($symb =~ /ext\.tool$/);
1.599     www      9892:     my $result;
                   9893: 
                   9894:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9895:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9896: 
1.745     raeburn  9897:     $result.=&selectfield(1,$is_tool).
1.601     www      9898:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9899:             <div>
                   9900:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9901:             </div>
                   9902:         </div>
                   9903:   </form>';
                   9904:     return $result;
                   9905: }
1.443     banghart 9906: 
1.621     www      9907: sub submit_options_download {
                   9908:     my ($request,$symb) = @_;
                   9909:     if (!$symb) {return '';}
                   9910: 
1.746     raeburn  9911:     my $is_tool = ($symb =~ /ext\.tool$/);
1.621     www      9912:     &commonJSfunctions($request);
                   9913: 
                   9914:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9915:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9916:     $result.='
                   9917: <h2>
1.750     raeburn  9918:   '.&mt('Select Students for whom to Download Submissions').'
1.745     raeburn  9919: </h2>'.&selectfield(1,$is_tool).'
1.621     www      9920:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9921:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9922:             </div>
                   9923:           </div>
1.600     www      9924: 
                   9925: 
1.621     www      9926:   </form>';
                   9927:     return $result;
                   9928: }
                   9929: 
1.443     banghart 9930: #--- Displays the submissions first page -------
                   9931: sub submit_options {
1.608     www      9932:     my ($request,$symb) = @_;
1.72      ng       9933:     if (!$symb) {return '';}
                   9934: 
1.746     raeburn  9935:     my $is_tool = ($symb =~ /ext\.tool$/);
1.118     ng       9936:     &commonJSfunctions($request);
1.473     albertel 9937:     my $result;
1.533     bisitz   9938: 
1.72      ng       9939:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9940: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.745     raeburn  9941:     $result.=&selectfield(1,$is_tool).'
1.601     www      9942:                 <input type="hidden" name="command" value="submission" /> 
                   9943: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9944:             </div>
                   9945:           </div>
                   9946: 
                   9947: 
                   9948:   </form>';
                   9949:     return $result;
                   9950: }
1.533     bisitz   9951: 
1.601     www      9952: sub selectfield {
1.745     raeburn  9953:    my ($full,$is_tool)=@_;
                   9954:    my %options;
                   9955:    if ($is_tool) {
                   9956:        %options =
                   9957:            (&transtatus_options,
                   9958:             'select_form_order' => ['yes','incorrect','all']);
                   9959:    } else {
                   9960:        %options = 
                   9961:            (&substatus_options,
                   9962:             'select_form_order' => ['yes','queued','graded','incorrect','all']);
                   9963:    }
1.601     www      9964:    my $result='<div class="LC_columnSection">
1.537     harmsja  9965:   
1.533     bisitz   9966:     <fieldset>
                   9967:       <legend>
                   9968:        '.&mt('Sections').'
                   9969:       </legend>
1.601     www      9970:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9971:     </fieldset>
1.537     harmsja  9972:   
1.533     bisitz   9973:     <fieldset>
                   9974:       <legend>
                   9975:         '.&mt('Groups').'
                   9976:       </legend>
                   9977:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9978:     </fieldset>
1.537     harmsja  9979:   
1.533     bisitz   9980:     <fieldset>
                   9981:       <legend>
                   9982:         '.&mt('Access Status').'
                   9983:       </legend>
1.601     www      9984:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9985:     </fieldset>';
                   9986:     if ($full) {
1.745     raeburn  9987:         my $heading = &mt('Submission Status');
                   9988:         if ($is_tool) {
                   9989:             $heading = &mt('Transaction Status');
                   9990:         }
                   9991:         $result.='
1.533     bisitz   9992:     <fieldset>
                   9993:       <legend>
1.745     raeburn  9994:         '.$heading.'
1.601     www      9995:       </legend>'.
1.635     raeburn  9996:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9997:    '</fieldset>';
                   9998:     }
                   9999:     $result.='</div><br />';
1.44      ng       10000:     return $result;
1.2       albertel 10001: }
                   10002: 
1.738     raeburn  10003: sub substatus_options {
                   10004:     return &Apache::lonlocal::texthash(
                   10005:                                       'yes'       => 'with submissions',
                   10006:                                       'queued'    => 'in grading queue',
                   10007:                                       'graded'    => 'with ungraded submissions',
                   10008:                                       'incorrect' => 'with incorrect submissions',
1.740     raeburn  10009:                                       'all'       => 'with any status',
                   10010:                                       );
1.738     raeburn  10011: }
                   10012: 
1.745     raeburn  10013: sub transtatus_options {
                   10014:     return &Apache::lonlocal::texthash(
                   10015:                                        'yes'       => 'with score transactions',
                   10016:                                        'incorrect' => 'with less than full credit',
                   10017:                                        'all'       => 'with any status',
                   10018:                                       );
                   10019: }
                   10020: 
1.285     albertel 10021: sub reset_perm {
                   10022:     undef(%perm);
                   10023: }
                   10024: 
                   10025: sub init_perm {
                   10026:     &reset_perm();
1.300     albertel 10027:     foreach my $test_perm ('vgr','mgr','opa') {
                   10028: 
                   10029: 	my $scope = $env{'request.course.id'};
                   10030: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10031: 
                   10032: 	    $scope .= '/'.$env{'request.course.sec'};
                   10033: 	    if ( $perm{$test_perm}=
                   10034: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10035: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10036: 	    } else {
                   10037: 		delete($perm{$test_perm});
                   10038: 	    }
1.285     albertel 10039: 	}
                   10040:     }
                   10041: }
                   10042: 
1.674     raeburn  10043: sub init_old_essays {
                   10044:     my ($symb,$apath,$adom,$aname) = @_;
                   10045:     if ($symb ne '') {
                   10046:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10047:         if (keys(%essays) > 0) {
                   10048:             $old_essays{$symb} = \%essays;
                   10049:         }
                   10050:     }
                   10051:     return;
                   10052: }
                   10053: 
                   10054: sub reset_old_essays {
                   10055:     undef(%old_essays);
                   10056: }
                   10057: 
1.400     www      10058: sub gather_clicker_ids {
1.408     albertel 10059:     my %clicker_ids;
1.400     www      10060: 
                   10061:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10062: 
                   10063:     # Set up a couple variables.
1.407     albertel 10064:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10065:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10066:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10067: 
1.407     albertel 10068:     foreach my $student (keys(%$classlist)) {
1.438     www      10069:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10070:         my $username = $classlist->{$student}->[$username_idx];
                   10071:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10072:         my $clickers =
1.408     albertel 10073: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10074:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10075:             $id=~s/^[\#0]+//;
1.421     www      10076:             $id=~s/[\-\:]//g;
1.407     albertel 10077:             if (exists($clicker_ids{$id})) {
1.408     albertel 10078: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10079:             } else {
1.408     albertel 10080: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10081:             }
                   10082:         }
                   10083:     }
1.407     albertel 10084:     return %clicker_ids;
1.400     www      10085: }
                   10086: 
1.402     www      10087: sub gather_adv_clicker_ids {
1.408     albertel 10088:     my %clicker_ids;
1.402     www      10089:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10090:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10091:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10092:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10093:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10094:             my ($puname,$pudom)=split(/\:/,$person);
                   10095:             my $clickers =
1.408     albertel 10096: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10097:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10098: 		$id=~s/^[\#0]+//;
1.421     www      10099:                 $id=~s/[\-\:]//g;
1.408     albertel 10100: 		if (exists($clicker_ids{$id})) {
                   10101: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10102: 		} else {
                   10103: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10104: 		}
1.405     www      10105:             }
1.402     www      10106:         }
                   10107:     }
1.407     albertel 10108:     return %clicker_ids;
1.402     www      10109: }
                   10110: 
1.413     www      10111: sub clicker_grading_parameters {
                   10112:     return ('gradingmechanism' => 'scalar',
                   10113:             'upfiletype' => 'scalar',
                   10114:             'specificid' => 'scalar',
                   10115:             'pcorrect' => 'scalar',
                   10116:             'pincorrect' => 'scalar');
                   10117: }
                   10118: 
1.400     www      10119: sub process_clicker {
1.608     www      10120:     my ($r,$symb)=@_;
1.400     www      10121:     if (!$symb) {return '';}
                   10122:     my $result=&checkforfile_js();
1.632     www      10123:     $result.=&Apache::loncommon::start_data_table().
                   10124:              &Apache::loncommon::start_data_table_header_row().
                   10125:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   10126:              &Apache::loncommon::end_data_table_header_row().
                   10127:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      10128: # Attempt to restore parameters from last session, set defaults if not present
                   10129:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10130:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10131:                                                  \%Saveable_Parameters);
                   10132:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10133:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10134:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10135:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10136: 
                   10137:     my %checked;
1.521     www      10138:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10139:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10140:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10141:        }
                   10142:     }
                   10143: 
1.632     www      10144:     my $upload=&mt("Evaluate File");
1.400     www      10145:     my $type=&mt("Type");
1.402     www      10146:     my $attendance=&mt("Award points just for participation");
                   10147:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10148:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10149:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10150:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10151:     my $pcorrect=&mt("Percentage points for correct solution");
                   10152:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10153:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  10154: 						   {'iclicker' => 'i>clicker',
1.666     www      10155:                                                     'interwrite' => 'interwrite PRS',
                   10156:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10157:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 10158:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      10159: function sanitycheck() {
                   10160: // Accept only integer percentages
                   10161:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10162:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10163: // Find out grading choice
                   10164:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10165:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10166:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10167:       }
                   10168:    }
                   10169: // By default, new choice equals user selection
                   10170:    newgradingchoice=gradingchoice;
                   10171: // Not good to give more points for false answers than correct ones
                   10172:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10173:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10174:    }
                   10175: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10176:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10177:       document.forms.gradesupload.pcorrect.value=100;
                   10178:       document.forms.gradesupload.pincorrect.value=100;
                   10179:    }
                   10180: // If the values are different, cannot be attendance only
                   10181:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10182:        (gradingchoice=='attendance')) {
                   10183:        newgradingchoice='personnel';
                   10184:    }
                   10185: // Change grading choice to new one
                   10186:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10187:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10188:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10189:       } else {
                   10190:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10191:       }
                   10192:    }
                   10193: // Remember the old state
                   10194:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10195: }
1.597     wenzelju 10196: ENDUPFORM
                   10197:     $result.= <<ENDUPFORM;
1.400     www      10198: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10199: <input type="hidden" name="symb" value="$symb" />
                   10200: <input type="hidden" name="command" value="processclickerfile" />
                   10201: <input type="file" name="upfile" size="50" />
                   10202: <br /><label>$type: $selectform</label>
1.632     www      10203: ENDUPFORM
                   10204:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10205:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   10206:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   10207: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10208: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10209: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10210: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10211: <br />&nbsp;&nbsp;&nbsp;
                   10212: <input type="text" name="givenanswer" size="50" />
1.413     www      10213: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      10214: ENDGRADINGFORM
                   10215:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   10216:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   10217:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   10218: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10219: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 10220: </form>'
1.632     www      10221: ENDPERCFORM
                   10222:     $result.='</td>'.
                   10223:              &Apache::loncommon::end_data_table_row().
                   10224:              &Apache::loncommon::end_data_table();
1.400     www      10225:     return $result;
                   10226: }
                   10227: 
                   10228: sub process_clicker_file {
1.608     www      10229:     my ($r,$symb)=@_;
1.400     www      10230:     if (!$symb) {return '';}
1.413     www      10231: 
                   10232:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10233:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10234:                                               \%Saveable_Parameters);
1.598     www      10235:     my $result='';
1.404     www      10236:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10237: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      10238: 	return $result;
1.404     www      10239:     }
1.522     www      10240:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10241:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      10242:         return $result;
1.521     www      10243:     }
1.522     www      10244:     my $foundgiven=0;
1.521     www      10245:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10246:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10247:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      10248:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10249:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10250:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10251:         $foundgiven=$#answers+1;
1.521     www      10252:     }
1.407     albertel 10253:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10254:     my %correct_ids;
1.404     www      10255:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10256: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10257:     }
                   10258:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10259: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10260: 	   $correct_id=~tr/a-z/A-Z/;
                   10261: 	   $correct_id=~s/\s//gs;
                   10262: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10263:            $correct_id=~s/[\-\:]//g;
1.414     www      10264:            if ($correct_id) {
                   10265: 	      $correct_ids{$correct_id}='specified';
                   10266:            }
                   10267:         }
1.400     www      10268:     }
1.404     www      10269:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10270: 	$result.=&mt('Score based on attendance only');
1.521     www      10271:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10272:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10273:     } else {
1.408     albertel 10274: 	my $number=0;
1.411     www      10275: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10276: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10277: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10278: 	    if ($correct_ids{$id} eq 'specified') {
                   10279: 		$result.=&mt('specified');
                   10280: 	    } else {
                   10281: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10282: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10283: 	    }
                   10284: 	    $number++;
                   10285: 	}
1.411     www      10286:         $result.="</p>\n";
1.710     bisitz   10287:         if ($number==0) {
                   10288:             $result .=
                   10289:                  &Apache::lonhtmlcommon::confirm_success(
                   10290:                      &mt('No IDs found to determine correct answer'),1);
                   10291:             return $result;
                   10292:         }
1.404     www      10293:     }
1.405     www      10294:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   10295:         $result .=
                   10296:             &Apache::lonhtmlcommon::confirm_success(
                   10297:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10298:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      10299:         return $result;
1.405     www      10300:     }
1.760     raeburn  10301:     my $mimetype;
                   10302:     if ($env{'form.upfiletype'} eq 'iclicker') {
                   10303:         my $mm = new File::MMagic;
                   10304:         $mimetype = $mm->checktype_contents($env{'form.upfile'});
                   10305:         unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
                   10306:             $result.= '<p>'.
                   10307:                 &Apache::lonhtmlcommon::confirm_success(
                   10308:                     &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
                   10309:             return $result;
                   10310:         }
                   10311:     } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
                   10312:         $result .= '<p>'.
                   10313:             &Apache::lonhtmlcommon::confirm_success(
                   10314:                 &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
                   10315:         return $result;
                   10316:     }
1.410     www      10317: 
                   10318: # Were able to get all the info needed, now analyze the file
                   10319: 
1.411     www      10320:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10321:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      10322:     $result.=&Apache::loncommon::start_data_table().
                   10323:              &Apache::loncommon::start_data_table_header_row().
                   10324:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   10325:              &Apache::loncommon::end_data_table_header_row().
                   10326:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   10327: <td>
1.410     www      10328: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10329: <input type="hidden" name="symb" value="$symb" />
                   10330: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      10331: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10332: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10333: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10334: ENDHEADER
1.522     www      10335:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10336:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10337:     } 
1.408     albertel 10338:     my %responses;
                   10339:     my @questiontitles;
1.405     www      10340:     my $errormsg='';
                   10341:     my $number=0;
                   10342:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.760     raeburn  10343:         if ($mimetype eq 'text/plain') {
                   10344:             ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
                   10345:         } elsif ($mimetype eq 'text/html') {
                   10346:             ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
                   10347:         }
                   10348:     } elsif ($env{'form.upfiletype'} eq 'interwrite') {
1.419     www      10349:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
1.760     raeburn  10350:     } elsif ($env{'form.upfiletype'} eq 'turning') {
1.666     www      10351:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10352:     }
1.411     www      10353:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10354:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10355:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10356:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10357:              '<br />';
1.522     www      10358:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10359:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      10360:        return $result;
1.522     www      10361:     } 
1.414     www      10362: # Remember Question Titles
                   10363: # FIXME: Possibly need delimiter other than ":"
                   10364:     for (my $i=0;$i<$number;$i++) {
                   10365:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10366:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10367:     }
1.411     www      10368:     my $correct_count=0;
                   10369:     my $student_count=0;
                   10370:     my $unknown_count=0;
1.414     www      10371: # Match answers with usernames
                   10372: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10373:     foreach my $id (keys(%responses)) {
1.410     www      10374:        if ($correct_ids{$id}) {
1.414     www      10375:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10376:           $correct_count++;
1.410     www      10377:        } elsif ($clicker_ids{$id}) {
1.437     www      10378:           if ($clicker_ids{$id}=~/\,/) {
                   10379: # More than one user with the same clicker!
1.632     www      10380:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10381:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10382:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      10383:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10384:                            "<select name='multi".$id."'>";
                   10385:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10386:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10387:              }
                   10388:              $result.='</select>';
                   10389:              $unknown_count++;
                   10390:           } else {
                   10391: # Good: found one and only one user with the right clicker
                   10392:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10393:              $student_count++;
                   10394:           }
1.410     www      10395:        } else {
1.632     www      10396:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   10397:                            &Apache::loncommon::start_data_table_row()."<td>".
                   10398:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      10399:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10400:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10401:                    "\n".&mt("Domain").": ".
                   10402:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      10403:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10404:           $unknown_count++;
1.410     www      10405:        }
1.405     www      10406:     }
1.412     www      10407:     $result.='<hr />'.
                   10408:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10409:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10410:        if ($correct_count==0) {
1.696     bisitz   10411:           $errormsg.="Found no correct answers for grading!";
1.412     www      10412:        } elsif ($correct_count>1) {
1.414     www      10413:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10414:        }
                   10415:     }
1.428     www      10416:     if ($number<1) {
                   10417:        $errormsg.="Found no questions.";
                   10418:     }
1.412     www      10419:     if ($errormsg) {
                   10420:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10421:     } else {
                   10422:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10423:     }
1.632     www      10424:     $result.='</form></td>'.
                   10425:              &Apache::loncommon::end_data_table_row().
                   10426:              &Apache::loncommon::end_data_table();
1.614     www      10427:     return $result;
1.400     www      10428: }
                   10429: 
1.405     www      10430: sub iclicker_eval {
1.406     www      10431:     my ($questiontitles,$responses)=@_;
1.405     www      10432:     my $number=0;
                   10433:     my $errormsg='';
                   10434:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10435:         my %components=&Apache::loncommon::record_sep($line);
                   10436:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10437: 	if ($entries[0] eq 'Question') {
                   10438: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10439: 		$$questiontitles[$number]=$entries[$i];
                   10440: 		$number++;
                   10441: 	    }
                   10442: 	}
                   10443: 	if ($entries[0]=~/^\#/) {
                   10444: 	    my $id=$entries[0];
                   10445: 	    my @idresponses;
                   10446: 	    $id=~s/^[\#0]+//;
                   10447: 	    for (my $i=0;$i<$number;$i++) {
                   10448: 		my $idx=3+$i*6;
1.644     www      10449:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10450: 		push(@idresponses,$entries[$idx]);
                   10451: 	    }
                   10452: 	    $$responses{$id}=join(',',@idresponses);
                   10453: 	}
1.405     www      10454:     }
                   10455:     return ($errormsg,$number);
                   10456: }
                   10457: 
1.760     raeburn  10458: sub iclickerxml_eval {
                   10459:     my ($questiontitles,$responses)=@_;
                   10460:     my $number=0;
                   10461:     my $errormsg='';
                   10462:     my @state;
                   10463:     my %respbyid;
                   10464:     my $p = HTML::Parser->new
                   10465:     (
                   10466:         xml_mode => 1,
                   10467:         start_h =>
                   10468:             [sub {
                   10469:                  my ($tagname,$attr) = @_;
                   10470:                  push(@state,$tagname);
                   10471:                  if ("@state" eq "ssn p") {
                   10472:                      my $title = $attr->{qn};
                   10473:                      $title =~ s/(^\s+|\s+$)//g;
                   10474:                      $questiontitles->[$number]=$title;
                   10475:                  } elsif ("@state" eq "ssn p v") {
                   10476:                      my $id = $attr->{id};
                   10477:                      my $entry = $attr->{ans};
                   10478:                      $id=~s/^[\#0]+//;
                   10479:                      $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
                   10480:                      $respbyid{$id}[$number] = $entry;
                   10481:                  }
                   10482:             }, "tagname, attr"],
                   10483:          end_h =>
                   10484:                [sub {
                   10485:                    my ($tagname) = @_;
                   10486:                    if ("@state" eq "ssn p") {
                   10487:                        $number++;
                   10488:                    }
                   10489:                    pop(@state);
                   10490:                 }, "tagname"],
                   10491:     );
                   10492: 
                   10493:     $p->parse($env{'form.upfile'});
                   10494:     $p->eof;
                   10495:     foreach my $id (keys(%respbyid)) {
                   10496:         $responses->{$id}=join(',',@{$respbyid{$id}});
                   10497:     }
                   10498:     return ($errormsg,$number);
                   10499: }
                   10500: 
1.419     www      10501: sub interwrite_eval {
                   10502:     my ($questiontitles,$responses)=@_;
                   10503:     my $number=0;
                   10504:     my $errormsg='';
1.420     www      10505:     my $skipline=1;
                   10506:     my $questionnumber=0;
                   10507:     my %idresponses=();
1.419     www      10508:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10509:         my %components=&Apache::loncommon::record_sep($line);
                   10510:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10511:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10512:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10513:         next if $skipline;
                   10514:         if ($entries[0]!=$questionnumber) {
                   10515:            $questionnumber=$entries[0];
                   10516:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10517:            $number++;
1.419     www      10518:         }
1.420     www      10519:         my $id=$entries[4];
                   10520:         $id=~s/^[\#0]+//;
1.421     www      10521:         $id=~s/^v\d*\://i;
                   10522:         $id=~s/[\-\:]//g;
1.420     www      10523:         $idresponses{$id}[$number]=$entries[6];
                   10524:     }
1.524     raeburn  10525:     foreach my $id (keys(%idresponses)) {
1.420     www      10526:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10527:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10528:     }
                   10529:     return ($errormsg,$number);
                   10530: }
                   10531: 
1.666     www      10532: sub turning_eval {
                   10533:     my ($questiontitles,$responses)=@_;
                   10534:     my $number=0;
                   10535:     my $errormsg='';
                   10536:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10537:         my %components=&Apache::loncommon::record_sep($line);
                   10538:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10539:         if ($#entries>$number) { $number=$#entries; }
                   10540:         my $id=$entries[0];
                   10541:         my @idresponses;
                   10542:         $id=~s/^[\#0]+//;
                   10543:         unless ($id) { next; }
                   10544:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10545:             $entries[$idx]=~s/\,/\;/g;
                   10546:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10547:             push(@idresponses,$entries[$idx]);
                   10548:         }
                   10549:         $$responses{$id}=join(',',@idresponses);
                   10550:     }
                   10551:     for (my $i=1; $i<=$number; $i++) {
                   10552:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10553:     }
                   10554:     return ($errormsg,$number);
                   10555: }
                   10556: 
                   10557: 
1.414     www      10558: sub assign_clicker_grades {
1.608     www      10559:     my ($r,$symb)=@_;
1.414     www      10560:     if (!$symb) {return '';}
1.416     www      10561: # See which part we are saving to
1.582     raeburn  10562:     my $res_error;
                   10563:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10564:     if ($res_error) {
                   10565:         return &navmap_errormsg();
                   10566:     }
1.416     www      10567: # FIXME: This should probably look for the first handgradeable part
                   10568:     my $part=$$partlist[0];
                   10569: # Start screen output
1.632     www      10570:     my $result=&Apache::loncommon::start_data_table().
                   10571:              &Apache::loncommon::start_data_table_header_row().
                   10572:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10573:              &Apache::loncommon::end_data_table_header_row().
                   10574:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10575: # Get correct result
                   10576: # FIXME: Possibly need delimiter other than ":"
                   10577:     my @correct=();
1.415     www      10578:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10579:     my $number=$env{'form.number'};
                   10580:     if ($gradingmechanism ne 'attendance') {
1.414     www      10581:        foreach my $key (keys(%env)) {
                   10582:           if ($key=~/^form\.correct\:/) {
                   10583:              my @input=split(/\,/,$env{$key});
                   10584:              for (my $i=0;$i<=$#input;$i++) {
                   10585:                  if (($correct[$i]) && ($input[$i]) &&
                   10586:                      ($correct[$i] ne $input[$i])) {
                   10587:                     $result.='<br /><span class="LC_warning">'.
                   10588:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10589:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10590:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10591:                     $correct[$i]=$input[$i];
                   10592:                  }
                   10593:              }
                   10594:           }
                   10595:        }
1.415     www      10596:        for (my $i=0;$i<$number;$i++) {
1.644     www      10597:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10598:              $result.='<br /><span class="LC_error">'.
                   10599:                       &mt('No correct result given for question "[_1]"!',
                   10600:                           $env{'form.question:'.$i}).'</span>';
                   10601:           }
                   10602:        }
1.644     www      10603:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10604:     }
                   10605: # Start grading
1.415     www      10606:     my $pcorrect=$env{'form.pcorrect'};
                   10607:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10608:     my $storecount=0;
1.632     www      10609:     my %users=();
1.415     www      10610:     foreach my $key (keys(%env)) {
1.420     www      10611:        my $user='';
1.415     www      10612:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10613:           $user=$1;
                   10614:        }
                   10615:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10616:           my $id=$1;
                   10617:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10618:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10619:           } elsif ($env{'form.multi'.$id}) {
                   10620:              $user=$env{'form.multi'.$id};
1.420     www      10621:           }
                   10622:        }
1.632     www      10623:        if ($user) {
                   10624:           if ($users{$user}) {
                   10625:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10626:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10627:                       '</span><br />';
                   10628:           }
                   10629:           $users{$user}=1; 
1.415     www      10630:           my @answer=split(/\,/,$env{$key});
                   10631:           my $sum=0;
1.522     www      10632:           my $realnumber=$number;
1.415     www      10633:           for (my $i=0;$i<$number;$i++) {
1.576     www      10634:              if  ($correct[$i] eq '-') {
                   10635:                 $realnumber--;
1.644     www      10636:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10637:                 if ($gradingmechanism eq 'attendance') {
                   10638:                    $sum+=$pcorrect;
1.576     www      10639:                 } elsif ($correct[$i] eq '*') {
1.522     www      10640:                    $sum+=$pcorrect;
1.415     www      10641:                 } else {
1.644     www      10642: # We actually grade if correct or not
                   10643:                    my $increment=$pincorrect;
                   10644: # Special case: numerical answer "0"
                   10645:                    if ($correct[$i] eq '0') {
                   10646:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10647:                          $increment=$pcorrect;
                   10648:                       }
                   10649: # General numerical answer, both evaluate to something non-zero
                   10650:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10651:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10652:                          $increment=$pcorrect;
                   10653:                       }
                   10654: # Must be just alphanumeric
                   10655:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10656:                       $increment=$pcorrect;
1.415     www      10657:                    }
1.644     www      10658:                    $sum+=$increment;
1.415     www      10659:                 }
                   10660:              }
                   10661:           }
1.522     www      10662:           my $ave=$sum/(100*$realnumber);
1.416     www      10663: # Store
                   10664:           my ($username,$domain)=split(/\:/,$user);
                   10665:           my %grades=();
                   10666:           $grades{"resource.$part.solved"}='correct_by_override';
                   10667:           $grades{"resource.$part.awarded"}=$ave;
                   10668:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10669:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10670:                                                  $env{'request.course.id'},
                   10671:                                                  $domain,$username);
                   10672:           if ($returncode ne 'ok') {
                   10673:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10674:           } else {
                   10675:              $storecount++;
                   10676:           }
1.415     www      10677:        }
                   10678:     }
                   10679: # We are done
1.549     hauer    10680:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10681:              '</td>'.
                   10682:              &Apache::loncommon::end_data_table_row().
                   10683:              &Apache::loncommon::end_data_table();
1.614     www      10684:     return $result;
1.414     www      10685: }
                   10686: 
1.582     raeburn  10687: sub navmap_errormsg {
                   10688:     return '<div class="LC_error">'.
                   10689:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10690:            &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  10691:            '</div>';
                   10692: }
1.607     droeschl 10693: 
1.609     www      10694: sub startpage {
1.754     raeburn  10695:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload) = @_;
                   10696:     my %args;
                   10697:     if ($onload) {
                   10698:          my %loaditems = (
                   10699:                         'onload' => $onload,
                   10700:                       );
                   10701:          $args{'add_entries'} = \%loaditems;
                   10702:     }
1.671     raeburn  10703:     if ($nomenu) {
1.754     raeburn  10704:         $args{'only_body'} = 1; 
1.759     raeburn  10705:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
1.671     raeburn  10706:     } else {
                   10707:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.754     raeburn  10708:         $args{'bread_crumbs'} = $crumbs;
                   10709:         $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
1.671     raeburn  10710:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10711:     }
1.613     www      10712:     unless ($nodisplayflag) {
1.759     raeburn  10713:         $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10714:     }
1.607     droeschl 10715: }
1.582     raeburn  10716: 
1.622     www      10717: sub select_problem {
                   10718:     my ($r)=@_;
1.632     www      10719:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.745     raeburn  10720:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,undef,undef,1));
1.622     www      10721:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10722:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10723: }
                   10724: 
1.1       albertel 10725: sub handler {
1.41      ng       10726:     my $request=$_[0];
1.434     albertel 10727:     &reset_caches();
1.646     raeburn  10728:     if ($request->header_only) {
                   10729:         &Apache::loncommon::content_type($request,'text/html');
                   10730:         $request->send_http_header;
                   10731:         return OK;
                   10732:     }
                   10733:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10734: 
1.664     raeburn  10735: # see what command we need to execute
                   10736: 
                   10737:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10738:     my $command=$commands[0];
                   10739: 
1.646     raeburn  10740:     &init_perm();
                   10741:     if (!$env{'request.course.id'}) {
1.664     raeburn  10742:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10743:                 ($command =~ /^scantronupload/)) {
                   10744:             # Not in a course.
                   10745:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10746:             return HTTP_NOT_ACCEPTABLE;
                   10747:         }
1.646     raeburn  10748:     } elsif (!%perm) {
                   10749:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10750:         return OK;
1.41      ng       10751:     }
1.646     raeburn  10752:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10753:     $request->send_http_header;
1.646     raeburn  10754: 
1.160     albertel 10755:     if ($#commands > 0) {
                   10756: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10757:     }
1.608     www      10758: 
                   10759: # see what the symb is
                   10760: 
                   10761:     my $symb=$env{'form.symb'};
                   10762:     unless ($symb) {
                   10763:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10764:        $symb=&Apache::lonnet::symbread($url);
                   10765:     }
1.646     raeburn  10766:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10767: 
1.513     foxr     10768:     $ssi_error = 0;
1.637     www      10769:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10770: #
1.637     www      10771: # Not called from a resource, but inside a course
1.601     www      10772: #    
1.622     www      10773:         &startpage($request,undef,[],1,1);
                   10774:         &select_problem($request);
1.41      ng       10775:     } else {
1.104     albertel 10776: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10777:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10778:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10779:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10780:                     &choose_task_version_form($symb,$env{'form.student'},
                   10781:                                               $env{'form.userdom'});
                   10782:             }
                   10783:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10784:             if ($versionform) {
                   10785:                 $request->print($versionform);
                   10786:             }
                   10787:             $request->print('<br clear="all" />');
1.611     www      10788: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10789:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10790:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10791:                 &choose_task_version_form($symb,$env{'form.student'},
                   10792:                                           $env{'form.userdom'},
                   10793:                                           $env{'form.inhibitmenu'});
                   10794:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10795:             if ($versionform) {
                   10796:                 $request->print($versionform);
                   10797:             }
                   10798:             $request->print('<br clear="all" />');
                   10799:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10800: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10801:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10802:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10803: 	    &pickStudentPage($request,$symb);
1.103     albertel 10804: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10805:             &startpage($request,$symb,
                   10806:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10807:                                        {href=>'',text=>'Select student'},
                   10808:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10809: 	    &displayPage($request,$symb);
1.104     albertel 10810: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10811:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10812:                                        {href=>'',text=>'Select student'},
                   10813:                                        {href=>'',text=>'Grade student'},
                   10814:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10815: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10816: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10817:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10818:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10819: 	    &processGroup($request,$symb);
1.104     albertel 10820: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10821:             &startpage($request,$symb);
                   10822: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10823: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10824:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10825: 	    $request->print(&submit_options($request,$symb));
1.598     www      10826:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10827:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10828:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10829:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10830:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10831:             $request->print(&submit_options_table($request,$symb));
1.598     www      10832:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10833:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10834:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10835: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10836:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10837: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10838: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10839:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10840:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10841: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10842: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10843:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10844:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10845:                                                                              text=>"Modify grades"},
                   10846:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10847: 	    $request->print(&editgrades($request,$symb));
1.602     www      10848:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10849:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10850:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10851: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10852:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10853:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10854: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10855:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10856:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10857:             $request->print(&process_clicker($request,$symb));
1.400     www      10858:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10859:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10860:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10861:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10862:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10863:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10864:                                        {href=>'', text=>'Process clicker file'},
                   10865:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10866:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10867: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10868:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10869: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10870: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10871:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10872: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10873: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10874:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10875: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10876: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10877: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10878:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10879: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10880: 	    } else {
1.257     albertel 10881: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10882: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10883: 		} else {
1.257     albertel 10884: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10885: 		}
1.627     www      10886:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10887: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10888: 	    }
1.246     albertel 10889: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10890:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10891: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10892: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.754     raeburn  10893:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   10894:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.612     www      10895: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10896:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10897:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10898:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10899: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10900:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10901: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10902: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10903:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10904: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10905:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10906:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10907: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.754     raeburn  10908:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
                   10909:                        undef,undef,undef,undef,'toggleScantab(document.rules);');
1.608     www      10910:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10911:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10912:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10913: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10914:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10915:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10916:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10917: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10918:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10919:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10920:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10921:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10922:             $request->print(&checkscantron_results($request,$symb));
                   10923:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10924:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10925:             $request->print(&submit_options_download($request,$symb));
                   10926:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10927:             &startpage($request,$symb,
                   10928:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
1.750     raeburn  10929:     {href=>'', text=>'Download submitted files'}]);
1.621     www      10930:             &submit_download_link($request,$symb);
1.106     albertel 10931: 	} elsif ($command) {
1.620     www      10932:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10933: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10934: 	}
1.2       albertel 10935:     }
1.513     foxr     10936:     if ($ssi_error) {
                   10937: 	&ssi_print_error($request);
                   10938:     }
1.671     raeburn  10939:     if ($env{'form.inhibitmenu'}) {
                   10940:         $request->print(&Apache::loncommon::end_page());
                   10941:     } else {
                   10942:         &Apache::lonquickgrades::endGradeScreen($request);
                   10943:     }
1.434     albertel 10944:     &reset_caches();
1.646     raeburn  10945:     return OK;
1.44      ng       10946: }
                   10947: 
1.1       albertel 10948: 1;
                   10949: 
1.13      albertel 10950: __END__;
1.531     jms      10951: 
                   10952: 
                   10953: =head1 NAME
                   10954: 
                   10955: Apache::grades
                   10956: 
                   10957: =head1 SYNOPSIS
                   10958: 
                   10959: Handles the viewing of grades.
                   10960: 
                   10961: This is part of the LearningOnline Network with CAPA project
                   10962: described at http://www.lon-capa.org.
                   10963: 
                   10964: =head1 OVERVIEW
                   10965: 
                   10966: Do an ssi with retries:
1.715     bisitz   10967: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10968: 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
                   10969: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10970: 
                   10971: At least the logic that drives this has been pulled out into loncommon.
                   10972: 
                   10973: 
                   10974: 
                   10975: ssi_with_retries - Does the server side include of a resource.
                   10976:                      if the ssi call returns an error we'll retry it up to
                   10977:                      the number of times requested by the caller.
1.715     bisitz   10978:                      If we still have a problem, no text is appended to the
1.531     jms      10979:                      output and we set some global variables.
                   10980:                      to indicate to the caller an SSI error occurred.  
                   10981:                      All of this is supposed to deal with the issues described
1.715     bisitz   10982:                      in LON-CAPA BZ 5631 see:
1.531     jms      10983:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10984:                      by informing the user that this happened.
                   10985: 
                   10986: Parameters:
                   10987:   resource   - The resource to include.  This is passed directly, without
                   10988:                interpretation to lonnet::ssi.
                   10989:   form       - The form hash parameters that guide the interpretation of the resource
                   10990:                
                   10991:   retries    - Number of retries allowed before giving up completely.
                   10992: Returns:
                   10993:   On success, returns the rendered resource identified by the resource parameter.
                   10994: Side Effects:
                   10995:   The following global variables can be set:
                   10996:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10997:                               It is up to the caller to initialize this to false
                   10998:                               if desired.
                   10999:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   11000:                               of the resource that could not be rendered by the ssi
                   11001:                               call.
                   11002:    ssi_error_message   - The error string fetched from the ssi response
                   11003:                               in the event of an error.
                   11004: 
                   11005: 
                   11006: =head1 HANDLER SUBROUTINE
                   11007: 
                   11008: ssi_with_retries()
                   11009: 
                   11010: =head1 SUBROUTINES
                   11011: 
                   11012: =over
                   11013: 
1.671     raeburn  11014: =head1 Routines to display previous version of a Task for a specific student
                   11015: 
                   11016: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   11017: can receive another opportunity. Access to tasks is slot-based. If a slot
                   11018: requires a proctor to check-in the student, a new version of the Task will
                   11019: be created when the student is checked in to the new opportunity.
                   11020: 
                   11021: If a particular student has tried two or more versions of a particular task,
                   11022: the submission screen provides a user with vgr privileges (e.g., a Course
                   11023: Coordinator) the ability to display a previous version worked on by the
                   11024: student.  By default, the current version is displayed. If a previous version
                   11025: has been selected for display, submission data are only shown that pertain
                   11026: to that particular version, and the interface to submit grades is not shown.
                   11027: 
                   11028: =over 4
                   11029: 
                   11030: =item show_previous_task_version()
                   11031: 
                   11032: Displays a specified version of a student's Task, as the student sees it.
                   11033: 
                   11034: Inputs: 2
                   11035:         request - request object
                   11036:         symb    - unique symb for current instance of resource
                   11037: 
                   11038: Output: None.
                   11039: 
                   11040: Side Effects: calls &show_problem() to print version of Task, with
                   11041:               version contained in form item: $env{'form.previousversion'}
                   11042: 
                   11043: =item choose_task_version_form()
                   11044: 
                   11045: Displays a web form used to select which version of a student's view of a
                   11046: Task should be displayed.  Either launches a pop-up window, or replaces
                   11047: content in existing pop-up, or replaces page in main window.
                   11048: 
                   11049: Inputs: 4
                   11050:         symb    - unique symb for current instance of resource
                   11051:         uname   - username of student
                   11052:         udom    - domain of student
                   11053:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11054:                   breadcrumbs etc., are displayed
                   11055: 
                   11056: Output: 4
                   11057:         current   - student's current version
                   11058:         displayed - student's version being displayed
                   11059:         result    - scalar containing HTML for web form used to switch to
                   11060:                     a different version (or a link to close window, if pop-up).
                   11061:         js        - javascript for processing selection in versions web form
                   11062: 
                   11063: Side Effects: None.
                   11064: 
                   11065: =item previous_display_javascript()
                   11066: 
                   11067: Inputs: 2
                   11068:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   11069:                   breadcrumbs etc., are displayed.
                   11070:         current - student's current version number.
                   11071: 
                   11072: Output: 1
                   11073:         js      - javascript for processing selection in versions web form.
                   11074: 
                   11075: Side Effects: None.
                   11076: 
                   11077: =back
                   11078: 
                   11079: =head1 Routines to process bubblesheet data.
                   11080: 
                   11081: =over 4
                   11082: 
1.531     jms      11083: =item scantron_get_correction() : 
                   11084: 
                   11085:    Builds the interface screen to interact with the operator to fix a
                   11086:    specific error condition in a specific scanline
                   11087: 
                   11088:  Arguments:
                   11089:     $r           - Apache request object
                   11090:     $i           - number of the current scanline
                   11091:     $scan_record - hash ref as returned from &scantron_parse_scanline()
1.758     raeburn  11092:     $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
1.531     jms      11093:     $line        - full contents of the current scanline
                   11094:     $error       - error condition, valid values are
                   11095:                    'incorrectCODE', 'duplicateCODE',
                   11096:                    'doublebubble', 'missingbubble',
                   11097:                    'duplicateID', 'incorrectID'
                   11098:     $arg         - extra information needed
                   11099:        For errors:
                   11100:          - duplicateID   - paper number that this studentID was seen before on
                   11101:          - duplicateCODE - array ref of the paper numbers this CODE was
                   11102:                            seen on before
                   11103:          - incorrectCODE - current incorrect CODE 
                   11104:          - doublebubble  - array ref of the bubble lines that have double
                   11105:                            bubble errors
                   11106:          - missingbubble - array ref of the bubble lines that have missing
                   11107:                            bubble errors
                   11108: 
1.691     raeburn  11109:    $randomorder - True if exam folder has randomorder set
                   11110:    $randompick  - True if exam folder has randompick set
                   11111:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   11112:                      for current line to question number used for same question
                   11113:                      in "Master Seqence" (as seen by Course Coordinator).
                   11114:    $startline   - Reference to hash where key is question number (0 is first)
                   11115:                   and value is number of first bubble line for current student
                   11116:                   or code-based randompick and/or randomorder.
                   11117: 
                   11118: 
                   11119: 
1.531     jms      11120: =item  scantron_get_maxbubble() : 
                   11121: 
1.582     raeburn  11122:    Arguments:
                   11123:        $nav_error  - Reference to scalar which is a flag to indicate a
                   11124:                       failure to retrieve a navmap object.
                   11125:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   11126:        calling routine should trap the error condition and display the warning
                   11127:        found in &navmap_errormsg().
                   11128: 
1.649     raeburn  11129:        $scantron_config - Reference to bubblesheet format configuration hash.
                   11130: 
1.531     jms      11131:    Returns the maximum number of bubble lines that are expected to
                   11132:    occur. Does this by walking the selected sequence rendering the
                   11133:    resource and then checking &Apache::lonxml::get_problem_counter()
                   11134:    for what the current value of the problem counter is.
                   11135: 
                   11136:    Caches the results to $env{'form.scantron_maxbubble'},
                   11137:    $env{'form.scantron.bubble_lines.n'}, 
                   11138:    $env{'form.scantron.first_bubble_line.n'} and
                   11139:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  11140:    which are the total number of bubble lines, the number of bubble
1.531     jms      11141:    lines for response n and number of the first bubble line for response n,
                   11142:    and a comma separated list of numbers of bubble lines for sub-questions
                   11143:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   11144: 
                   11145: 
                   11146: =item  scantron_validate_missingbubbles() : 
                   11147: 
                   11148:    Validates all scanlines in the selected file to not have any
                   11149:     answers that don't have bubbles that have not been verified
                   11150:     to be bubble free.
                   11151: 
                   11152: =item  scantron_process_students() : 
                   11153: 
1.659     raeburn  11154:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      11155: 
                   11156:    The parsed scanline hash is added to %env 
                   11157: 
                   11158:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   11159:    foreach resource , with the form data of
                   11160: 
                   11161: 	'submitted'     =>'scantron' 
                   11162: 	'grade_target'  =>'grade',
                   11163: 	'grade_username'=> username of student
                   11164: 	'grade_domain'  => domain of student
                   11165: 	'grade_courseid'=> of course
                   11166: 	'grade_symb'    => symb of resource to grade
                   11167: 
                   11168:     This triggers a grading pass. The problem grading code takes care
                   11169:     of converting the bubbled letter information (now in %env) into a
                   11170:     valid submission.
                   11171: 
                   11172: =item  scantron_upload_scantron_data() :
                   11173: 
1.659     raeburn  11174:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      11175: 
                   11176: =item  scantron_upload_scantron_data_save() : 
                   11177: 
                   11178:    Adds a provided bubble information data file to the course if user
                   11179:    has the correct privileges to do so. 
                   11180: 
                   11181: =item  valid_file() :
                   11182: 
                   11183:    Validates that the requested bubble data file exists in the course.
                   11184: 
                   11185: =item  scantron_download_scantron_data() : 
                   11186: 
                   11187:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  11188:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      11189:    course.
                   11190: 
                   11191: =item  scantron_validate_ID() : 
                   11192: 
                   11193:    Validates all scanlines in the selected file to not have any
1.556     weissno  11194:    invalid or underspecified student/employee IDs
1.531     jms      11195: 
1.582     raeburn  11196: =item navmap_errormsg() :
                   11197: 
                   11198:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  11199:    Should be called whenever the request to instantiate a navmap object fails.
                   11200: 
                   11201: =back
1.582     raeburn  11202: 
1.531     jms      11203: =back
                   11204: 
                   11205: =cut

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