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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.575   ! www         4: # $Id: grades.pm,v 1.574 2009/05/14 14:24:07 bisitz 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.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.170     albertel   46: use String::Similarity;
1.359     www        47: use LONCAPA;
                     48: 
1.315     bowersj2   49: use POSIX qw(floor);
1.87      www        50: 
1.435     foxr       51: 
1.513     foxr       52: 
1.435     foxr       53: my %perm=();
1.447     foxr       54: 
1.513     foxr       55: #  These variables are used to recover from ssi errors
                     56: 
                     57: my $ssi_retries = 5;
                     58: my $ssi_error;
                     59: my $ssi_error_resource;
                     60: my $ssi_error_message;
                     61: 
                     62: 
                     63: sub ssi_with_retries {
                     64:     my ($resource, $retries, %form) = @_;
                     65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     66:     if ($response->is_error) {
                     67: 	$ssi_error          = 1;
                     68: 	$ssi_error_resource = $resource;
                     69: 	$ssi_error_message  = $response->code . " " . $response->message;
                     70:     }
                     71: 
                     72:     return $content;
                     73: 
                     74: }
                     75: #
                     76: #  Prodcuces an ssi retry failure error message to the user:
                     77: #
                     78: 
                     79: sub ssi_print_error {
                     80:     my ($r) = @_;
1.516     raeburn    81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     82:     $r->print('
                     83: <br />
                     84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     85: <p>
                     86: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     88: '.&mt('Error:').' '.$ssi_error_message.'
                     89: </p>
                     90: <p>'.
                     91: &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 />'.
                     92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     93: '</p>');
                     94:     return;
1.513     foxr       95: }
                     96: 
1.44      ng         97: #
1.146     albertel   98: # --- Retrieve the parts from the metadata file.---
1.44      ng         99: sub getpartlist {
1.324     albertel  100:     my ($symb) = @_;
1.439     albertel  101: 
                    102:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    103:     my $res      = $navmap->getBySymb($symb);
                    104:     my $partlist = $res->parts();
                    105:     my $url      = $res->src();
                    106:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    107: 
1.146     albertel  108:     my @stores;
1.439     albertel  109:     foreach my $part (@{ $partlist }) {
1.146     albertel  110: 	foreach my $key (@metakeys) {
                    111: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    112: 	}
                    113:     }
                    114:     return @stores;
1.2       albertel  115: }
                    116: 
1.44      ng        117: # --- Get the symbolic name of a problem and the url
1.324     albertel  118: sub get_symb {
1.173     albertel  119:     my ($request,$silent) = @_;
1.257     albertel  120:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    121:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  122:     if ($symb eq '') { 
                    123: 	if (!$silent) {
                    124: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    125: 	    return ();
                    126: 	}
                    127:     }
1.418     albertel  128:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  129:     return ($symb);
1.32      ng        130: }
                    131: 
1.129     ng        132: #--- Format fullname, username:domain if different for display
                    133: #--- Use anywhere where the student names are listed
                    134: sub nameUserString {
                    135:     my ($type,$fullname,$uname,$udom) = @_;
                    136:     if ($type eq 'header') {
1.485     albertel  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        138:     } else {
1.398     albertel  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        141:     }
                    142: }
                    143: 
1.44      ng        144: #--- Get the partlist and the response type for a given problem. ---
                    145: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        146: sub response_type {
1.324     albertel  147:     my ($symb) = shift;
1.377     albertel  148: 
                    149:     my $navmap = Apache::lonnavmaps::navmap->new();
                    150:     my $res = $navmap->getBySymb($symb);
                    151:     my $partlist = $res->parts();
1.392     albertel  152:     my %vPart = 
                    153: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  154:     my (%response_types,%handgrade);
                    155:     foreach my $part (@{ $partlist }) {
1.392     albertel  156: 	next if (%vPart && !exists($vPart{$part}));
                    157: 
1.377     albertel  158: 	my @types = $res->responseType($part);
                    159: 	my @ids = $res->responseIds($part);
                    160: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    161: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    162: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    163: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    164: 				     '.handgrade',$symb);
1.41      ng        165: 	}
                    166:     }
1.377     albertel  167:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        168: }
                    169: 
1.375     albertel  170: sub flatten_responseType {
                    171:     my ($responseType) = @_;
                    172:     my @part_response_id =
                    173: 	map { 
                    174: 	    my $part = $_;
                    175: 	    map {
                    176: 		[$part,$_]
                    177: 		} sort(keys(%{ $responseType->{$part} }));
                    178: 	} sort(keys(%$responseType));
                    179:     return @part_response_id;
                    180: }
                    181: 
1.207     albertel  182: sub get_display_part {
1.324     albertel  183:     my ($partID,$symb)=@_;
1.207     albertel  184:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    185:     if (defined($display) and $display ne '') {
1.398     albertel  186: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  187:     } else {
                    188: 	$display=$partID;
                    189:     }
                    190:     return $display;
                    191: }
1.269     raeburn   192: 
1.118     ng        193: #--- Show resource title
                    194: #--- and parts and response type
                    195: sub showResourceInfo {
1.324     albertel  196:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  197:     my $col=3;
                    198:     if ($checkboxes) { $col=4; }
1.398     albertel  199:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    200:     $result .='<table border="0">';
1.324     albertel  201:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        202:     my %resptype = ();
1.122     ng        203:     my $hdgrade='no';
1.154     albertel  204:     my %partsseen;
1.524     raeburn   205:     foreach my $partID (sort(keys(%$responseType))) {
                    206: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
1.375     albertel  207: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    208: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    209: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    210: 	    $result.='<tr>';
                    211: 	    if ($checkboxes) {
                    212: 		if (exists($partsseen{$partID})) {
                    213: 		    $result.="<td>&nbsp;</td>";
                    214: 		} else {
1.401     albertel  215: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  216: 		}
                    217: 		$partsseen{$partID}=1;
1.154     albertel  218: 	    }
1.375     albertel  219: 	    my $display_part=&get_display_part($partID,$symb);
1.539     riegler   220: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
                    221:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
                    222: 		'<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
1.485     albertel  223: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
1.154     albertel  224: 	}
1.118     ng        225:     }
                    226:     $result.='</table>'."\n";
1.147     albertel  227:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        228: }
                    229: 
1.434     albertel  230: sub reset_caches {
                    231:     &reset_analyze_cache();
                    232:     &reset_perm();
                    233: }
                    234: 
                    235: {
                    236:     my %analyze_cache;
1.557     raeburn   237:     my %analyze_cache_formkeys;
1.148     albertel  238: 
1.434     albertel  239:     sub reset_analyze_cache {
                    240: 	undef(%analyze_cache);
1.557     raeburn   241:         undef(%analyze_cache_formkeys);
1.434     albertel  242:     }
                    243: 
                    244:     sub get_analyze {
1.557     raeburn   245: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  246: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   247: 	if (exists($analyze_cache{$key})) {
                    248:             my $getupdate = 0;
                    249:             if (ref($add_to_hash) eq 'HASH') {
                    250:                 foreach my $item (keys(%{$add_to_hash})) {
                    251:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    252:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    253:                             $getupdate = 1;
                    254:                             last;
                    255:                         }
                    256:                     } else {
                    257:                         $getupdate = 1;
                    258:                     }
                    259:                 }
                    260:             }
                    261:             if (!$getupdate) {
                    262:                 return $analyze_cache{$key};
                    263:             }
                    264:         }
1.434     albertel  265: 
                    266: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    267: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   268:         my %form = ('grade_target'      => 'analyze',
                    269:                     'grade_domain'      => $udom,
                    270:                     'grade_symb'        => $symb,
                    271:                     'grade_courseid'    =>  $env{'request.course.id'},
                    272:                     'grade_username'    => $uname,
                    273:                     'grade_noincrement' => $no_increment);
                    274:         if (ref($add_to_hash)) {
                    275:             %form = (%form,%{$add_to_hash});
                    276:         } 
                    277: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  278: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    279: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   280:         if (ref($add_to_hash) eq 'HASH') {
                    281:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    282:         } else {
                    283:             $analyze_cache_formkeys{$key} = {};
                    284:         }
1.434     albertel  285: 	return $analyze_cache{$key} = \%analyze;
                    286:     }
                    287: 
                    288:     sub get_order {
1.525     raeburn   289: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    290: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  291: 	return $analyze->{"$partid.$respid.shown"};
                    292:     }
                    293: 
                    294:     sub get_radiobutton_correct_foil {
                    295: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    296: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   297:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    298:         if (ref($foils) eq 'ARRAY') {
                    299: 	    foreach my $foil (@{$foils}) {
                    300: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    301: 		    return $foil;
                    302: 	        }
1.434     albertel  303: 	    }
                    304: 	}
                    305:     }
1.554     raeburn   306: 
                    307:     sub scantron_partids_tograde {
1.557     raeburn   308:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   309:         my (%analysis,@parts);
                    310:         if (ref($resource)) {
                    311:             my $symb = $resource->symb();
1.557     raeburn   312:             my $add_to_form;
                    313:             if ($check_for_randomlist) {
                    314:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    315:             }
                    316:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   317:             if (ref($analyze) eq 'HASH') {
                    318:                 %analysis = %{$analyze};
                    319:             }
                    320:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    321:                 foreach my $part (@{$analysis{'parts'}}) {
                    322:                     my ($id,$respid) = split(/\./,$part);
                    323:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    324:                         push(@parts,$part);
                    325:                     }
                    326:                 }
                    327:             }
                    328:         }
                    329:         return (\%analysis,\@parts);
                    330:     }
                    331: 
1.148     albertel  332: }
1.434     albertel  333: 
1.118     ng        334: #--- Clean response type for display
1.335     albertel  335: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    336: #        response types only.
1.118     ng        337: sub cleanRecord {
1.336     albertel  338:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    339: 	$uname,$udom) = @_;
1.398     albertel  340:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  341:     if ($response =~ /^(option|rank)$/) {
                    342: 	my %answer=&Apache::lonnet::str2hash($answer);
                    343: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    344: 	my ($toprow,$bottomrow);
                    345: 	foreach my $foil (@$order) {
                    346: 	    if ($grading{$foil} == 1) {
                    347: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    348: 	    } else {
                    349: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    350: 	    }
1.398     albertel  351: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  352: 	}
                    353: 	return '<blockquote><table border="1">'.
1.466     albertel  354: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    355: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  356: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    357:     } elsif ($response eq 'match') {
                    358: 	my %answer=&Apache::lonnet::str2hash($answer);
                    359: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    360: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    361: 	my ($toprow,$middlerow,$bottomrow);
                    362: 	foreach my $foil (@$order) {
                    363: 	    my $item=shift(@items);
                    364: 	    if ($grading{$foil} == 1) {
                    365: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  366: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  367: 	    } else {
                    368: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  369: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  370: 	    }
1.398     albertel  371: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        372: 	}
1.126     ng        373: 	return '<blockquote><table border="1">'.
1.466     albertel  374: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    375: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  376: 	    $middlerow.'</tr>'.
1.466     albertel  377: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  378: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    379:     } elsif ($response eq 'radiobutton') {
                    380: 	my %answer=&Apache::lonnet::str2hash($answer);
                    381: 	my ($toprow,$bottomrow);
1.434     albertel  382: 	my $correct = 
                    383: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    384: 	foreach my $foil (@$order) {
1.148     albertel  385: 	    if (exists($answer{$foil})) {
1.434     albertel  386: 		if ($foil eq $correct) {
1.466     albertel  387: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  388: 		} else {
1.466     albertel  389: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  390: 		}
                    391: 	    } else {
1.466     albertel  392: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  393: 	    }
1.398     albertel  394: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  395: 	}
                    396: 	return '<blockquote><table border="1">'.
1.466     albertel  397: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    398: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  399: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    400:     } elsif ($response eq 'essay') {
1.257     albertel  401: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        402: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  403: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    404: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        405: 
1.257     albertel  406: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    407: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    408: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    409: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    410: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    411: 	    $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        412: 	}
1.166     albertel  413: 	$answer =~ s-\n-<br />-g;
                    414: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  415:     } elsif ( $response eq 'organic') {
                    416: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    417: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    418: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    419: 	return $result;
1.335     albertel  420:     } elsif ( $response eq 'Task') {
                    421: 	if ( $answer eq 'SUBMITTED') {
                    422: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  423: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  424: 	    return $result;
                    425: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    426: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    427: 			       keys(%{$record}));
                    428: 	    return join('<br />',($version,@matches));
                    429: 			       
                    430: 			       
                    431: 	} else {
                    432: 	    my $result =
                    433: 		'<p>'
                    434: 		.&mt('Overall result: [_1]',
                    435: 		     $record->{$version."resource.$respid.$partid.status"})
                    436: 		.'</p>';
                    437: 	    
                    438: 	    $result .= '<ul>';
                    439: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    440: 			     keys(%{$record}));
                    441: 	    foreach my $grade (sort(@grade)) {
                    442: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    443: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    444: 				     $dim, $record->{$grade}).
                    445: 			  '</li>';
                    446: 	    }
                    447: 	    $result.='</ul>';
                    448: 	    return $result;
                    449: 	}
1.440     albertel  450:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    451: 	$answer = 
                    452: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    453: 							      $answer);
1.122     ng        454:     }
1.118     ng        455:     return $answer;
                    456: }
                    457: 
                    458: #-- A couple of common js functions
                    459: sub commonJSfunctions {
                    460:     my $request = shift;
                    461:     $request->print(<<COMMONJSFUNCTIONS);
                    462: <script type="text/javascript" language="javascript">
                    463:     function radioSelection(radioButton) {
                    464: 	var selection=null;
                    465: 	if (radioButton.length > 1) {
                    466: 	    for (var i=0; i<radioButton.length; i++) {
                    467: 		if (radioButton[i].checked) {
                    468: 		    return radioButton[i].value;
                    469: 		}
                    470: 	    }
                    471: 	} else {
                    472: 	    if (radioButton.checked) return radioButton.value;
                    473: 	}
                    474: 	return selection;
                    475:     }
                    476: 
                    477:     function pullDownSelection(selectOne) {
                    478: 	var selection="";
                    479: 	if (selectOne.length > 1) {
                    480: 	    for (var i=0; i<selectOne.length; i++) {
                    481: 		if (selectOne[i].selected) {
                    482: 		    return selectOne[i].value;
                    483: 		}
                    484: 	    }
                    485: 	} else {
1.138     albertel  486:             // only one value it must be the selected one
                    487: 	    return selectOne.value;
1.118     ng        488: 	}
                    489:     }
                    490: </script>
                    491: COMMONJSFUNCTIONS
                    492: }
                    493: 
1.44      ng        494: #--- Dumps the class list with usernames,list of sections,
                    495: #--- section, ids and fullnames for each user.
                    496: sub getclasslist {
1.449     banghart  497:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  498:     my @getsec;
1.450     banghart  499:     my @getgroup;
1.442     banghart  500:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  501:     if (!ref($getsec)) {
                    502: 	if ($getsec ne '' && $getsec ne 'all') {
                    503: 	    @getsec=($getsec);
                    504: 	}
                    505:     } else {
                    506: 	@getsec=@{$getsec};
                    507:     }
                    508:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  509:     if (!ref($getgroup)) {
                    510: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    511: 	    @getgroup=($getgroup);
                    512: 	}
                    513:     } else {
                    514: 	@getgroup=@{$getgroup};
                    515:     }
                    516:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  517: 
1.449     banghart  518:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  519:     # Bail out if we were unable to get the classlist
1.56      matthew   520:     return if (! defined($classlist));
1.449     banghart  521:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   522:     #
                    523:     my %sections;
                    524:     my %fullnames;
1.205     matthew   525:     foreach my $student (keys(%$classlist)) {
                    526:         my $end      = 
                    527:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    528:         my $start    = 
                    529:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    530:         my $id       = 
                    531:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    532:         my $section  = 
                    533:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    534:         my $fullname = 
                    535:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    536:         my $status   = 
                    537:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  538:         my $group   = 
                    539:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        540: 	# filter students according to status selected
1.442     banghart  541: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    542: 	    if (!($stu_status =~ $status)) {
1.450     banghart  543: 		delete($classlist->{$student});
1.76      ng        544: 		next;
                    545: 	    }
                    546: 	}
1.450     banghart  547: 	# filter students according to groups selected
1.453     banghart  548: 	my @stu_groups = split(/,/,$group);
1.450     banghart  549: 	if (@getgroup) {
                    550: 	    my $exclude = 1;
1.454     banghart  551: 	    foreach my $grp (@getgroup) {
                    552: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  553: 	            if ($stu_group eq $grp) {
                    554: 	                $exclude = 0;
                    555:     	            } 
1.450     banghart  556: 	        }
1.453     banghart  557:     	        if (($grp eq 'none') && !$group) {
                    558:         	        $exclude = 0;
                    559:         	}
1.450     banghart  560: 	    }
                    561: 	    if ($exclude) {
                    562: 	        delete($classlist->{$student});
                    563: 	    }
                    564: 	}
1.205     matthew   565: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  566: 	if (&canview($section)) {
1.291     albertel  567: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  568: 		$sections{$section}++;
1.450     banghart  569: 		if ($classlist->{$student}) {
                    570: 		    $fullnames{$student}=$fullname;
                    571: 		}
1.103     albertel  572: 	    } else {
1.205     matthew   573: 		delete($classlist->{$student});
1.103     albertel  574: 	    }
                    575: 	} else {
1.205     matthew   576: 	    delete($classlist->{$student});
1.103     albertel  577: 	}
1.44      ng        578:     }
                    579:     my %seen = ();
1.56      matthew   580:     my @sections = sort(keys(%sections));
                    581:     return ($classlist,\@sections,\%fullnames);
1.44      ng        582: }
                    583: 
1.103     albertel  584: sub canmodify {
                    585:     my ($sec)=@_;
                    586:     if ($perm{'mgr'}) {
                    587: 	if (!defined($perm{'mgr_section'})) {
                    588: 	    # can modify whole class
                    589: 	    return 1;
                    590: 	} else {
                    591: 	    if ($sec eq $perm{'mgr_section'}) {
                    592: 		#can modify the requested section
                    593: 		return 1;
                    594: 	    } else {
                    595: 		# can't modify the request section
                    596: 		return 0;
                    597: 	    }
                    598: 	}
                    599:     }
                    600:     #can't modify
                    601:     return 0;
                    602: }
                    603: 
                    604: sub canview {
                    605:     my ($sec)=@_;
                    606:     if ($perm{'vgr'}) {
                    607: 	if (!defined($perm{'vgr_section'})) {
                    608: 	    # can modify whole class
                    609: 	    return 1;
                    610: 	} else {
                    611: 	    if ($sec eq $perm{'vgr_section'}) {
                    612: 		#can modify the requested section
                    613: 		return 1;
                    614: 	    } else {
                    615: 		# can't modify the request section
                    616: 		return 0;
                    617: 	    }
                    618: 	}
                    619:     }
                    620:     #can't modify
                    621:     return 0;
                    622: }
                    623: 
1.44      ng        624: #--- Retrieve the grade status of a student for all the parts
                    625: sub student_gradeStatus {
1.324     albertel  626:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  627:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        628:     my %partstatus = ();
                    629:     foreach (@$partlist) {
1.128     ng        630: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        631: 	$status              = 'nothing' if ($status eq '');
                    632: 	$partstatus{$_}      = $status;
                    633: 	my $subkey           = "resource.$_.submitted_by";
                    634: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    635:     }
                    636:     return %partstatus;
                    637: }
                    638: 
1.45      ng        639: # hidden form and javascript that calls the form
                    640: # Use by verifyscript and viewgrades
                    641: # Shows a student's view of problem and submission
                    642: sub jscriptNform {
1.324     albertel  643:     my ($symb) = @_;
1.442     banghart  644:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        645:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    646: 	'    function viewOneStudent(user,domain) {'."\n".
                    647: 	'	document.onestudent.student.value = user;'."\n".
                    648: 	'	document.onestudent.userdom.value = domain;'."\n".
                    649: 	'	document.onestudent.submit();'."\n".
                    650: 	'    }'."\n".
                    651: 	'</script>'."\n";
                    652:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  653: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  654: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    655: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  656: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        657: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    658: 	'<input type="hidden" name="student" value="" />'."\n".
                    659: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    660: 	'</form>'."\n";
                    661:     return $jscript;
                    662: }
1.39      ng        663: 
1.447     foxr      664: 
                    665: 
1.315     bowersj2  666: # Given the score (as a number [0-1] and the weight) what is the final
                    667: # point value? This function will round to the nearest tenth, third,
                    668: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  669: sub compute_points {
1.315     bowersj2  670:     my ($score, $weight) = @_;
                    671:     
                    672:     my $tolerance = .00001;
                    673:     my $points = $score * $weight;
                    674: 
                    675:     # Check for nearness to 1/x.
                    676:     my $check_for_nearness = sub {
                    677:         my ($factor) = @_;
                    678:         my $num = ($points * $factor) + $tolerance;
                    679:         my $floored_num = floor($num);
1.316     albertel  680:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  681:             return $floored_num / $factor;
                    682:         }
                    683:         return $points;
                    684:     };
                    685: 
                    686:     $points = $check_for_nearness->(10);
                    687:     $points = $check_for_nearness->(3);
                    688:     $points = $check_for_nearness->(4);
                    689:     
                    690:     return $points;
                    691: }
                    692: 
1.44      ng        693: #------------------ End of general use routines --------------------
1.87      www       694: 
                    695: #
                    696: # Find most similar essay
                    697: #
                    698: 
                    699: sub most_similar {
1.426     albertel  700:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       701: 
                    702: # ignore spaces and punctuation
                    703: 
                    704:     $uessay=~s/\W+/ /gs;
                    705: 
1.282     www       706: # ignore empty submissions (occuring when only files are sent)
                    707: 
                    708:     unless ($uessay=~/\w+/) { return ''; }
                    709: 
1.87      www       710: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       711:     my $limit=0.6;
1.87      www       712:     my $sname='';
                    713:     my $sdom='';
                    714:     my $scrsid='';
                    715:     my $sessay='';
                    716: # go through all essays ...
1.426     albertel  717:     foreach my $tkey (keys(%$old_essays)) {
                    718: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       719: # ... except the same student
1.426     albertel  720:         next if (($tname eq $uname) && ($tdom eq $udom));
                    721: 	my $tessay=$old_essays->{$tkey};
                    722: 	$tessay=~s/\W+/ /gs;
1.87      www       723: # String similarity gives up if not even limit
1.426     albertel  724: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       725: # Found one
1.426     albertel  726: 	if ($tsimilar>$limit) {
                    727: 	    $limit=$tsimilar;
                    728: 	    $sname=$tname;
                    729: 	    $sdom=$tdom;
                    730: 	    $scrsid=$tcrsid;
                    731: 	    $sessay=$old_essays->{$tkey};
                    732: 	}
1.87      www       733:     }
1.88      www       734:     if ($limit>0.6) {
1.87      www       735:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    736:     } else {
                    737:        return ('','','','',0);
                    738:     }
                    739: }
                    740: 
1.44      ng        741: #-------------------------------------------------------------------
                    742: 
                    743: #------------------------------------ Receipt Verification Routines
1.45      ng        744: #
1.44      ng        745: #--- Check whether a receipt number is valid.---
                    746: sub verifyreceipt {
                    747:     my $request  = shift;
                    748: 
1.257     albertel  749:     my $courseid = $env{'request.course.id'};
1.184     www       750:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  751: 	$env{'form.receipt'};
1.44      ng        752:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  753:     my ($symb)   = &get_symb($request);
1.44      ng        754: 
1.487     albertel  755:     my $title.=
                    756: 	'<h3><span class="LC_info">'.
1.553     biermanm  757: 	&mt('Verifying  Receipt No. [_1]',$receipt).
1.487     albertel  758: 	'</span></h3>'."\n".
                    759: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    760: 	'</h4>'."\n";
1.44      ng        761: 
                    762:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   763:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  764:     
                    765:     my $receiptparts=0;
1.390     albertel  766:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    767: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  768:     my $parts=['0'];
1.324     albertel  769:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.486     albertel  770:     
                    771:     my $header = 
                    772: 	&Apache::loncommon::start_data_table().
                    773: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  774: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    775: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    776: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  777:     if ($receiptparts) {
1.487     albertel  778: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  779:     }
                    780:     $header.=
                    781: 	&Apache::loncommon::end_data_table_header_row();
                    782: 
1.294     albertel  783:     foreach (sort 
                    784: 	     {
                    785: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    786: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    787: 		 }
                    788: 		 return $a cmp $b;
                    789: 	     } (keys(%$fullname))) {
1.44      ng        790: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  791: 	foreach my $part (@$parts) {
                    792: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  793: 		$contents.=
                    794: 		    &Apache::loncommon::start_data_table_row().
                    795: 		    '<td>&nbsp;'."\n".
1.177     albertel  796: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  797: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  798: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    799: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    800: 		if ($receiptparts) {
                    801: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    802: 		}
1.486     albertel  803: 		$contents.= 
                    804: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  805: 		
                    806: 		$matches++;
                    807: 	    }
1.44      ng        808: 	}
                    809:     }
                    810:     if ($matches == 0) {
1.487     albertel  811: 	$string = $title.&mt('No match found for the above receipt.');
1.44      ng        812:     } else {
1.324     albertel  813: 	$string = &jscriptNform($symb).$title.
1.487     albertel  814: 	    '<p>'.
                    815: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
                    816: 	    '</p>'.
1.486     albertel  817: 	    $header.
                    818: 	    $contents.
                    819: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        820:     }
1.324     albertel  821:     return $string.&show_grading_menu_form($symb);
1.44      ng        822: }
                    823: 
                    824: #--- This is called by a number of programs.
                    825: #--- Called from the Grading Menu - View/Grade an individual student
                    826: #--- Also called directly when one clicks on the subm button 
                    827: #    on the problem page.
1.30      ng        828: sub listStudents {
1.41      ng        829:     my ($request) = shift;
1.49      albertel  830: 
1.324     albertel  831:     my ($symb) = &get_symb($request);
1.257     albertel  832:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    833:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    834:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  835:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  836:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    837:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  838:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    839: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  840: 
1.548     bisitz    841:     my $result='<h3><span class="LC_info">&nbsp;'
                    842: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  843: 	.'</span></h3>';
1.118     ng        844: 
1.324     albertel  845:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  846: 
1.559     raeburn   847:     my %lt = &Apache::lonlocal::texthash (
                    848: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    849: 		'single'   => 'Please select the student before clicking on the Next button.',
                    850: 	     );
1.45      ng        851:     $request->print(<<LISTJAVASCRIPT);
                    852: <script type="text/javascript" language="javascript">
1.110     ng        853:     function checkSelect(checkBox) {
                    854: 	var ctr=0;
                    855: 	var sense="";
                    856: 	if (checkBox.length > 1) {
                    857: 	    for (var i=0; i<checkBox.length; i++) {
                    858: 		if (checkBox[i].checked) {
                    859: 		    ctr++;
                    860: 		}
                    861: 	    }
1.485     albertel  862: 	    sense = '$lt{'multiple'}';
1.110     ng        863: 	} else {
                    864: 	    if (checkBox.checked) {
                    865: 		ctr = 1;
                    866: 	    }
1.485     albertel  867: 	    sense = '$lt{'single'}';
1.110     ng        868: 	}
                    869: 	if (ctr == 0) {
1.485     albertel  870: 	    alert(sense);
1.110     ng        871: 	    return false;
                    872: 	}
                    873: 	document.gradesub.submit();
                    874:     }
                    875: 
                    876:     function reLoadList(formname) {
1.112     ng        877: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        878: 	formname.command.value = 'submission';
                    879: 	formname.submit();
                    880:     }
1.45      ng        881: </script>
                    882: LISTJAVASCRIPT
                    883: 
1.118     ng        884:     &commonJSfunctions($request);
1.41      ng        885:     $request->print($result);
1.39      ng        886: 
1.401     albertel  887:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    888:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  889:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  890: 	"\n".$table;
                    891: 	
1.561     bisitz    892:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    893:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    894:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    895:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    896:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    897:                   .&Apache::lonhtmlcommon::row_closure();
                    898:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    899:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    900:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    901:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    902:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  903: 
                    904:     my $submission_options;
1.257     albertel  905:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  906: 	$submission_options.=
                    907: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  908:     }
1.442     banghart  909:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    910:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  911:     $env{'form.Status'} = $saveStatus;
1.485     albertel  912:     $submission_options.=
                    913: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                    914: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                    915: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                    916: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
1.561     bisitz    917:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    918:                   .$submission_options
                    919:                   .&Apache::lonhtmlcommon::row_closure();
                    920: 
                    921:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    922:                   .'<select name="increment">'
                    923:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    924:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    925:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    926:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    927:                   .'</select>'
                    928:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  929: 
                    930:     $gradeTable .= 
1.432     banghart  931:         &build_section_inputs().
1.45      ng        932: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  933: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    934: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    935: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    936: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  937: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        938: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    939: 
1.257     albertel  940:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    941: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        942:     } else {
1.561     bisitz    943:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    944:                       .&Apache::lonhtmlcommon::StatusOptions(
                    945:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    946:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        947:     }
1.112     ng        948: 
1.561     bisitz    949:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    950:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    951:                   .&Apache::lonhtmlcommon::row_closure(1)
                    952:                   .&Apache::lonhtmlcommon::end_pick_box();
                    953: 
                    954:     $gradeTable .= '<p>'
                    955:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
                    956:                   .'<input type="hidden" name="command" value="processGroup" />'
                    957:                   .'</p>';
1.249     albertel  958: 
                    959: # checkall buttons
                    960:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        961:     $gradeTable.='<input type="button" '."\n".
1.45      ng        962: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.539     riegler   963: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  964:     $gradeTable.=&check_buttons();
1.450     banghart  965:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  966:     $gradeTable.= &Apache::loncommon::start_data_table().
                    967: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        968:     my $loop = 0;
                    969:     while ($loop < 2) {
1.485     albertel  970: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    971: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  972: 	if ($env{'form.showgrading'} eq 'yes' 
                    973: 	    && $submitonly ne 'queued'
                    974: 	    && $submitonly ne 'all') {
1.485     albertel  975: 	    foreach my $part (sort(@$partlist)) {
                    976: 		my $display_part=
                    977: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    978: 		$gradeTable.=
                    979: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        980: 	    }
1.301     albertel  981: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  982: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        983: 	}
                    984: 	$loop++;
1.126     ng        985: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        986:     }
1.474     albertel  987:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        988: 
1.45      ng        989:     my $ctr = 0;
1.294     albertel  990:     foreach my $student (sort 
                    991: 			 {
                    992: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    993: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    994: 			     }
                    995: 			     return $a cmp $b;
                    996: 			 }
                    997: 			 (keys(%$fullname))) {
1.41      ng        998: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  999: 
1.110     ng       1000: 	my %status = ();
1.301     albertel 1001: 
                   1002: 	if ($submitonly eq 'queued') {
                   1003: 	    my %queue_status = 
                   1004: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1005: 							$udom,$uname);
                   1006: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1007: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1008: 	}
                   1009: 
                   1010: 	if ($env{'form.showgrading'} eq 'yes' 
                   1011: 	    && $submitonly ne 'queued'
                   1012: 	    && $submitonly ne 'all') {
1.324     albertel 1013: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1014: 	    my $submitted = 0;
1.164     albertel 1015: 	    my $graded = 0;
1.248     albertel 1016: 	    my $incorrect = 0;
1.110     ng       1017: 	    foreach (keys(%status)) {
1.145     albertel 1018: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1019: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1020: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1021: 		
1.110     ng       1022: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1023: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1024: 		    $submitted = 0;
1.150     albertel 1025: 		    my ($part)=split(/\./,$partid);
1.110     ng       1026: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1027: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1028: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1029: 		}
1.41      ng       1030: 	    }
1.248     albertel 1031: 	    
1.156     albertel 1032: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1033: 				     $submitonly eq 'incorrect' ||
                   1034: 				     $submitonly eq 'graded'));
1.248     albertel 1035: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1036: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1037: 	}
1.34      ng       1038: 
1.45      ng       1039: 	$ctr++;
1.249     albertel 1040: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1041:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1042: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1043: 	    if ($ctr%2 ==1) {
                   1044: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1045: 	    }
1.126     ng       1046: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1047:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1048:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1049: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1050: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1051: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1052: 
1.257     albertel 1053: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1054: 		foreach (sort(keys(%status))) {
1.485     albertel 1055: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1056: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1057: 		}
1.41      ng       1058: 	    }
1.126     ng       1059: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1060: 	    if ($ctr%2 ==0) {
                   1061: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1062: 	    }
1.41      ng       1063: 	}
                   1064:     }
1.110     ng       1065:     if ($ctr%2 ==1) {
1.126     ng       1066: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1067: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1068: 		&& $submitonly ne 'queued'
                   1069: 		&& $submitonly ne 'all') {
1.110     ng       1070: 		foreach (@$partlist) {
                   1071: 		    $gradeTable.='<td>&nbsp;</td>';
                   1072: 		}
1.301     albertel 1073: 	    } elsif ($submitonly eq 'queued') {
                   1074: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1075: 	    }
1.474     albertel 1076: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1077:     }
                   1078: 
1.474     albertel 1079:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1080: 	'<input type="button" '.
                   1081: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.539     riegler  1082: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1083:     if ($ctr == 0) {
1.96      albertel 1084: 	my $num_students=(scalar(keys(%$fullname)));
                   1085: 	if ($num_students eq 0) {
1.485     albertel 1086: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1087: 	} else {
1.171     albertel 1088: 	    my $submissions='submissions';
                   1089: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1090: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1091: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1092: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1093: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1094: 		    $num_students).
                   1095: 		'</span><br />';
1.96      albertel 1096: 	}
1.46      ng       1097:     } elsif ($ctr == 1) {
1.474     albertel 1098: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1099:     }
1.324     albertel 1100:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1101:     $request->print($gradeTable);
1.44      ng       1102:     return '';
1.10      ng       1103: }
                   1104: 
1.44      ng       1105: #---- Called from the listStudents routine
1.249     albertel 1106: 
                   1107: sub check_script {
                   1108:     my ($form, $type)=@_;
                   1109:     my $chkallscript='<script type="text/javascript">
                   1110:     function checkall() {
                   1111:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1112:             ele = document.forms.'.$form.'.elements[i];
                   1113:             if (ele.name == "'.$type.'") {
                   1114:             document.forms.'.$form.'.elements[i].checked=true;
                   1115:                                        }
                   1116:         }
                   1117:     }
                   1118: 
                   1119:     function checksec() {
                   1120:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1121:             ele = document.forms.'.$form.'.elements[i];
                   1122:            string = document.forms.'.$form.'.chksec.value;
                   1123:            if
                   1124:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1125:               document.forms.'.$form.'.elements[i].checked=true;
                   1126:             }
                   1127:         }
                   1128:     }
                   1129: 
                   1130: 
                   1131:     function uncheckall() {
                   1132:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1133:             ele = document.forms.'.$form.'.elements[i];
                   1134:             if (ele.name == "'.$type.'") {
                   1135:             document.forms.'.$form.'.elements[i].checked=false;
                   1136:                                        }
                   1137:         }
                   1138:     }
                   1139: 
                   1140: </script>'."\n";
                   1141:     return $chkallscript;
                   1142: }
                   1143: 
                   1144: sub check_buttons {
1.485     albertel 1145:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1146:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1147:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1148:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1149:     return $buttons;
                   1150: }
                   1151: 
1.44      ng       1152: #     Displays the submissions for one student or a group of students
1.34      ng       1153: sub processGroup {
1.41      ng       1154:     my ($request)  = shift;
                   1155:     my $ctr        = 0;
1.155     albertel 1156:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1157:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1158: 
1.396     banghart 1159:     foreach my $student (@stuchecked) {
                   1160: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1161: 	$env{'form.student'}        = $uname;
                   1162: 	$env{'form.userdom'}        = $udom;
                   1163: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1164: 	&submission($request,$ctr,$total);
                   1165: 	$ctr++;
                   1166:     }
                   1167:     return '';
1.35      ng       1168: }
1.34      ng       1169: 
1.44      ng       1170: #------------------------------------------------------------------------------------
                   1171: #
                   1172: #-------------------------- Next few routines handles grading by student, essentially
                   1173: #                           handles essay response type problem/part
                   1174: #
                   1175: #--- Javascript to handle the submission page functionality ---
                   1176: sub sub_page_js {
                   1177:     my $request = shift;
1.539     riegler  1178: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.44      ng       1179:     $request->print(<<SUBJAVASCRIPT);
                   1180: <script type="text/javascript" language="javascript">
1.71      ng       1181:     function updateRadio(formname,id,weight) {
1.125     ng       1182: 	var gradeBox = formname["GD_BOX"+id];
                   1183: 	var radioButton = formname["RADVAL"+id];
                   1184: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1185: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1186: 	gradeBox.value = pts;
                   1187: 	var resetbox = false;
                   1188: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1189: 	    alert("$alertmsg"+pts);
1.71      ng       1190: 	    for (var i=0; i<radioButton.length; i++) {
                   1191: 		if (radioButton[i].checked) {
                   1192: 		    gradeBox.value = i;
                   1193: 		    resetbox = true;
                   1194: 		}
                   1195: 	    }
                   1196: 	    if (!resetbox) {
                   1197: 		formtextbox.value = "";
                   1198: 	    }
                   1199: 	    return;
1.44      ng       1200: 	}
1.71      ng       1201: 
                   1202: 	if (pts > weight) {
                   1203: 	    var resp = confirm("You entered a value ("+pts+
                   1204: 			       ") greater than the weight for the part. Accept?");
                   1205: 	    if (resp == false) {
1.125     ng       1206: 		gradeBox.value = oldpts;
1.71      ng       1207: 		return;
                   1208: 	    }
1.44      ng       1209: 	}
1.13      albertel 1210: 
1.71      ng       1211: 	for (var i=0; i<radioButton.length; i++) {
                   1212: 	    radioButton[i].checked=false;
                   1213: 	    if (pts == i && pts != "") {
                   1214: 		radioButton[i].checked=true;
                   1215: 	    }
                   1216: 	}
                   1217: 	updateSelect(formname,id);
1.125     ng       1218: 	formname["stores"+id].value = "0";
1.41      ng       1219:     }
1.5       albertel 1220: 
1.72      ng       1221:     function writeBox(formname,id,pts) {
1.125     ng       1222: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1223: 	if (checkSolved(formname,id) == 'update') {
                   1224: 	    gradeBox.value = pts;
                   1225: 	} else {
1.125     ng       1226: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1227: 	    gradeBox.value = oldpts;
1.125     ng       1228: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1229: 	    for (var i=0; i<radioButton.length; i++) {
                   1230: 		radioButton[i].checked=false;
1.72      ng       1231: 		if (i == oldpts) {
1.71      ng       1232: 		    radioButton[i].checked=true;
                   1233: 		}
                   1234: 	    }
1.41      ng       1235: 	}
1.125     ng       1236: 	formname["stores"+id].value = "0";
1.71      ng       1237: 	updateSelect(formname,id);
                   1238: 	return;
1.41      ng       1239:     }
1.44      ng       1240: 
1.71      ng       1241:     function clearRadBox(formname,id) {
                   1242: 	if (checkSolved(formname,id) == 'noupdate') {
                   1243: 	    updateSelect(formname,id);
                   1244: 	    return;
                   1245: 	}
1.125     ng       1246: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1247: 	for (var i=0; i<gradeSelect.length; i++) {
                   1248: 	    if (gradeSelect[i].selected) {
                   1249: 		var selectx=i;
                   1250: 	    }
                   1251: 	}
1.125     ng       1252: 	var stores = formname["stores"+id];
1.71      ng       1253: 	if (selectx == stores.value) { return };
1.125     ng       1254: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1255: 	gradeBox.value = "";
1.125     ng       1256: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1257: 	for (var i=0; i<radioButton.length; i++) {
                   1258: 	    radioButton[i].checked=false;
                   1259: 	}
                   1260: 	stores.value = selectx;
                   1261:     }
1.5       albertel 1262: 
1.71      ng       1263:     function checkSolved(formname,id) {
1.125     ng       1264: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1265: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1266: 	    if (!reply) {return "noupdate";}
1.120     ng       1267: 	    formname.overRideScore.value = 'yes';
1.41      ng       1268: 	}
1.71      ng       1269: 	return "update";
1.13      albertel 1270:     }
1.71      ng       1271: 
                   1272:     function updateSelect(formname,id) {
1.125     ng       1273: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1274: 	return;
1.41      ng       1275:     }
1.33      ng       1276: 
1.121     ng       1277: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1278:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1279: 	formname.gradeOpt.value = val;
1.71      ng       1280: 	if (val == "Save & Next") {
                   1281: 	    for (i=0;i<=total;i++) {
                   1282: 		for (j=0;j<parttot;j++) {
1.125     ng       1283: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1284: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1285: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1286: 			if (points == "") {
1.125     ng       1287: 			    var name = formname["name"+i].value;
1.129     ng       1288: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1289: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1290: 					       ", part "+partid+". Continue?");
1.71      ng       1291: 			    if (resp == false) {
1.125     ng       1292: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1293: 				return false;
                   1294: 			    }
                   1295: 			}
                   1296: 		    }
                   1297: 		    
                   1298: 		}
                   1299: 	    }
                   1300: 	    
                   1301: 	}
1.121     ng       1302: 	if (val == "Grade Student") {
                   1303: 	    formname.showgrading.value = "yes";
                   1304: 	    if (formname.Status.value == "") {
                   1305: 		formname.Status.value = "Active";
                   1306: 	    }
                   1307: 	    formname.studentNo.value = total;
                   1308: 	}
1.120     ng       1309: 	formname.submit();
                   1310:     }
                   1311: 
1.71      ng       1312: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1313:     function checkSubmitPage(formname,total) {
                   1314: 	noscore = new Array(100);
                   1315: 	var ptr = 0;
                   1316: 	for (i=1;i<total;i++) {
1.125     ng       1317: 	    var partid = formname["q_"+i].value;
1.127     ng       1318: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1319: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1320: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1321: 		if (points == "" && status != "correct_by_student") {
                   1322: 		    noscore[ptr] = i;
                   1323: 		    ptr++;
                   1324: 		}
                   1325: 	    }
                   1326: 	}
                   1327: 	if (ptr != 0) {
                   1328: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1329: 	    var prolist = "";
                   1330: 	    if (ptr == 1) {
                   1331: 		prolist = noscore[0];
                   1332: 	    } else {
                   1333: 		var i = 0;
                   1334: 		while (i < ptr-1) {
                   1335: 		    prolist += noscore[i]+", ";
                   1336: 		    i++;
                   1337: 		}
                   1338: 		prolist += "and "+noscore[i];
                   1339: 	    }
                   1340: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1341: 	    if (resp == false) {
                   1342: 		return false;
                   1343: 	    }
                   1344: 	}
1.45      ng       1345: 
1.71      ng       1346: 	formname.submit();
                   1347:     }
                   1348: </script>
                   1349: SUBJAVASCRIPT
                   1350: }
1.45      ng       1351: 
1.71      ng       1352: #--- javascript for essay type problem --
                   1353: sub sub_page_kw_js {
                   1354:     my $request = shift;
1.80      ng       1355:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1356:     &commonJSfunctions($request);
1.350     albertel 1357: 
1.351     albertel 1358:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1359:     <script text="text/javascript">
                   1360:     function checkInput() {
                   1361:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1362:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1363:       var usrctr = document.msgcenter.usrctr.value;
                   1364:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1365:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1366: 
                   1367:       var msgchk = "";
                   1368:       if (document.msgcenter.subchk.checked) {
                   1369:          msgchk = "msgsub,";
                   1370:       }
                   1371:       var includemsg = 0;
                   1372:       for (var i=1; i<=nmsg; i++) {
                   1373:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1374:           var frmmsg = document.msgcenter["msg"+i];
                   1375:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1376:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1377:           showflg.value = "1";
                   1378:           var chkbox = document.msgcenter["msgn"+i];
                   1379:           if (chkbox.checked) {
                   1380:              msgchk += "savemsg"+i+",";
                   1381:              includemsg = 1;
                   1382:           }
                   1383:       }
                   1384:       if (document.msgcenter.newmsgchk.checked) {
                   1385:          msgchk += "newmsg"+usrctr;
                   1386:          includemsg = 1;
                   1387:       }
                   1388:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1389:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1390:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1391:       includemsg.value = msgchk;
                   1392: 
                   1393:       self.close()
                   1394: 
                   1395:     }
                   1396:     </script>
                   1397: INNERJS
                   1398: 
1.351     albertel 1399:     my $inner_js_highlight_central=<<INNERJS;
                   1400:  <script type="text/javascript">
                   1401:     function updateChoice(flag) {
                   1402:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1403:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1404:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1405:       opener.document.SCORE.refresh.value = "on";
                   1406:       if (opener.document.SCORE.keywords.value!=""){
                   1407:          opener.document.SCORE.submit();
                   1408:       }
                   1409:       self.close()
                   1410:     }
                   1411: </script>
                   1412: INNERJS
                   1413: 
                   1414:     my $start_page_msg_central = 
                   1415:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1416: 				       {'js_ready'  => 1,
                   1417: 					'only_body' => 1,
                   1418: 					'bgcolor'   =>'#FFFFFF',});
                   1419:     my $end_page_msg_central = 
                   1420: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1421: 
                   1422: 
                   1423:     my $start_page_highlight_central = 
                   1424:         &Apache::loncommon::start_page('Highlight Central',
                   1425: 				       $inner_js_highlight_central,
1.350     albertel 1426: 				       {'js_ready'  => 1,
                   1427: 					'only_body' => 1,
                   1428: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1429:     my $end_page_highlight_central = 
1.350     albertel 1430: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1431: 
1.219     www      1432:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1433:     $docopen=~s/^document\.//;
1.539     riegler  1434:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.71      ng       1435:     $request->print(<<SUBJAVASCRIPT);
                   1436: <script type="text/javascript" language="javascript">
1.45      ng       1437: 
1.44      ng       1438: //===================== Show list of keywords ====================
1.122     ng       1439:   function keywords(formname) {
                   1440:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1441:     if (nret==null) return;
1.122     ng       1442:     formname.keywords.value = nret;
1.44      ng       1443: 
1.122     ng       1444:     if (formname.keywords.value != "") {
1.128     ng       1445: 	formname.refresh.value = "on";
1.122     ng       1446: 	formname.submit();
1.44      ng       1447:     }
                   1448:     return;
                   1449:   }
                   1450: 
                   1451: //===================== Script to view submitted by ==================
                   1452:   function viewSubmitter(submitter) {
                   1453:     document.SCORE.refresh.value = "on";
                   1454:     document.SCORE.NCT.value = "1";
                   1455:     document.SCORE.unamedom0.value = submitter;
                   1456:     document.SCORE.submit();
                   1457:     return;
                   1458:   }
                   1459: 
                   1460: //===================== Script to add keyword(s) ==================
                   1461:   function getSel() {
                   1462:     if (document.getSelection) txt = document.getSelection();
                   1463:     else if (document.selection) txt = document.selection.createRange().text;
                   1464:     else return;
                   1465:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1466:     if (cleantxt=="") {
1.539     riegler  1467: 	alert("$alertmsg");
1.44      ng       1468: 	return;
                   1469:     }
                   1470:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1471:     if (nret==null) return;
1.127     ng       1472:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1473:     if (document.SCORE.keywords.value != "") {
1.127     ng       1474: 	document.SCORE.refresh.value = "on";
1.44      ng       1475: 	document.SCORE.submit();
                   1476:     }
                   1477:     return;
                   1478:   }
                   1479: 
                   1480: //====================== Script for composing message ==============
1.80      ng       1481:    // preload images
                   1482:    img1 = new Image();
                   1483:    img1.src = "$iconpath/mailbkgrd.gif";
                   1484:    img2 = new Image();
                   1485:    img2.src = "$iconpath/mailto.gif";
                   1486: 
1.44      ng       1487:   function msgCenter(msgform,usrctr,fullname) {
                   1488:     var Nmsg  = msgform.savemsgN.value;
                   1489:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1490:     var subject = msgform.msgsub.value;
1.127     ng       1491:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1492:     re = /msgsub/;
                   1493:     var shwsel = "";
                   1494:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1495:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1496:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1497:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1498: 	var testmsg = "savemsg"+i+",";
                   1499: 	re = new RegExp(testmsg,"g");
1.44      ng       1500: 	shwsel = "";
                   1501: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1502: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1503: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1504: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1505: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1506:     }
1.125     ng       1507:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1508:     shwsel = "";
                   1509:     re = /newmsg/;
                   1510:     if (re.test(msgchk)) { shwsel = "checked" }
                   1511:     newMsg(newmsg,shwsel);
                   1512:     msgTail(); 
                   1513:     return;
                   1514:   }
                   1515: 
1.123     ng       1516:   function checkEntities(strx) {
                   1517:     if (strx.length == 0) return strx;
                   1518:     var orgStr = ["&", "<", ">", '"']; 
                   1519:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1520:     var counter = 0;
                   1521:     while (counter < 4) {
                   1522: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1523: 	counter++;
                   1524:     }
                   1525:     return strx;
                   1526:   }
                   1527: 
                   1528:   function strReplace(strx, orgStr, newStr) {
                   1529:     return strx.split(orgStr).join(newStr);
                   1530:   }
                   1531: 
1.44      ng       1532:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1533:     var height = 70*Nmsg+250;
1.44      ng       1534:     var scrollbar = "no";
                   1535:     if (height > 600) {
                   1536: 	height = 600;
                   1537: 	scrollbar = "yes";
                   1538:     }
1.118     ng       1539:     var xpos = (screen.width-600)/2;
                   1540:     xpos = (xpos < 0) ? '0' : xpos;
                   1541:     var ypos = (screen.height-height)/2-30;
                   1542:     ypos = (ypos < 0) ? '0' : ypos;
                   1543: 
1.206     albertel 1544:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1545:     pWin.focus();
                   1546:     pDoc = pWin.document;
1.219     www      1547:     pDoc.$docopen;
1.351     albertel 1548:     pDoc.write('$start_page_msg_central');
1.76      ng       1549: 
                   1550:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1551:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1552:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1553: 
1.564     bisitz   1554:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1555:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1556:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1557: }
                   1558:     function displaySubject(msg,shwsel) {
1.76      ng       1559:     pDoc = pWin.document;
                   1560:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1561:     pDoc.write("<td>Subject<\\/td>");
                   1562:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1563:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1564: }
                   1565: 
1.72      ng       1566:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1567:     pDoc = pWin.document;
                   1568:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1569:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1570:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1571:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1572: }
                   1573: 
                   1574:   function newMsg(newmsg,shwsel) {
1.76      ng       1575:     pDoc = pWin.document;
                   1576:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1577:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1578:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1579:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1580: }
                   1581: 
                   1582:   function msgTail() {
1.76      ng       1583:     pDoc = pWin.document;
1.465     albertel 1584:     pDoc.write("<\\/table>");
                   1585:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1586:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1587:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1588:     pDoc.write("<\\/form>");
1.351     albertel 1589:     pDoc.write('$end_page_msg_central');
1.128     ng       1590:     pDoc.close();
1.44      ng       1591: }
                   1592: 
                   1593: //====================== Script for keyword highlight options ==============
                   1594:   function kwhighlight() {
                   1595:     var kwclr    = document.SCORE.kwclr.value;
                   1596:     var kwsize   = document.SCORE.kwsize.value;
                   1597:     var kwstyle  = document.SCORE.kwstyle.value;
                   1598:     var redsel = "";
                   1599:     var grnsel = "";
                   1600:     var blusel = "";
                   1601:     if (kwclr=="red")   {var redsel="checked"};
                   1602:     if (kwclr=="green") {var grnsel="checked"};
                   1603:     if (kwclr=="blue")  {var blusel="checked"};
                   1604:     var sznsel = "";
                   1605:     var sz1sel = "";
                   1606:     var sz2sel = "";
                   1607:     if (kwsize=="0")  {var sznsel="checked"};
                   1608:     if (kwsize=="+1") {var sz1sel="checked"};
                   1609:     if (kwsize=="+2") {var sz2sel="checked"};
                   1610:     var synsel = "";
                   1611:     var syisel = "";
                   1612:     var sybsel = "";
                   1613:     if (kwstyle=="")    {var synsel="checked"};
                   1614:     if (kwstyle=="<i>") {var syisel="checked"};
                   1615:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1616:     highlightCentral();
                   1617:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1618:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1619:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1620:     highlightend();
                   1621:     return;
                   1622:   }
                   1623: 
                   1624:   function highlightCentral() {
1.76      ng       1625: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1626:     var xpos = (screen.width-400)/2;
                   1627:     xpos = (xpos < 0) ? '0' : xpos;
                   1628:     var ypos = (screen.height-330)/2-30;
                   1629:     ypos = (ypos < 0) ? '0' : ypos;
                   1630: 
1.206     albertel 1631:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1632:     hwdWin.focus();
                   1633:     var hDoc = hwdWin.document;
1.219     www      1634:     hDoc.$docopen;
1.351     albertel 1635:     hDoc.write('$start_page_highlight_central');
1.76      ng       1636:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1637:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1638: 
1.564     bisitz   1639:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1640:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1641:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1642:   }
                   1643: 
                   1644:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1645:     var hDoc = hwdWin.document;
                   1646:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1647:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1648:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1649:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1650:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1651:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1652:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1653:     hDoc.write("<\\/tr>");
1.44      ng       1654:   }
                   1655: 
                   1656:   function highlightend() { 
1.76      ng       1657:     var hDoc = hwdWin.document;
1.465     albertel 1658:     hDoc.write("<\\/table>");
                   1659:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1660:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1661:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1662:     hDoc.write("<\\/form>");
1.351     albertel 1663:     hDoc.write('$end_page_highlight_central');
1.128     ng       1664:     hDoc.close();
1.44      ng       1665:   }
                   1666: 
                   1667: </script>
                   1668: SUBJAVASCRIPT
                   1669: }
                   1670: 
1.349     albertel 1671: sub get_increment {
1.348     bowersj2 1672:     my $increment = $env{'form.increment'};
                   1673:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1674:         $increment != .1) {
                   1675:         $increment = 1;
                   1676:     }
                   1677:     return $increment;
                   1678: }
                   1679: 
1.71      ng       1680: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1681: sub gradeBox {
1.322     albertel 1682:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1683:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1684: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1685:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1686:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1687:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1688:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1689:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1690: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1691:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1692:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1693:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1694: 				       [$partid]);
                   1695:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1696:     if ($last_resets{$partid}) {
                   1697:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1698:     }
1.485     albertel 1699:     $result.='<table border="0"><tr>';
1.71      ng       1700:     my $ctr = 0;
1.348     bowersj2 1701:     my $thisweight = 0;
1.349     albertel 1702:     my $increment = &get_increment();
1.485     albertel 1703: 
                   1704:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1705:     while ($thisweight<=$wgt) {
1.532     bisitz   1706: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1707: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1708: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1709: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1710: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1711:         $thisweight += $increment;
1.71      ng       1712: 	$ctr++;
                   1713:     }
1.485     albertel 1714:     $radio.='</tr></table>';
                   1715: 
                   1716:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1717: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1718: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1719: 	$wgt.')" /></td>'."\n";
1.485     albertel 1720:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1721: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.540     riegler  1722: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
1.485     albertel 1723:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1724: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1725:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1726: 	$line.='<option></option>'.
                   1727: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1728:     } else {
1.485     albertel 1729: 	$line.='<option selected="selected"></option>'.
                   1730: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1731:     }
1.485     albertel 1732:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1733: 
                   1734: 
1.540     riegler  1735: 	#&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
1.485     albertel 1736:     $result .= 
1.540     riegler  1737: 	    '<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 1738:     
                   1739:     $result.='</tr></table>'."\n";
1.71      ng       1740:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1741: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1742: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1743: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1744:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1745:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1746:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1747:         $aggtries.'" />'."\n";
1.323     banghart 1748:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1749:     return $result;
                   1750: }
1.322     albertel 1751: 
                   1752: sub handback_box {
1.323     banghart 1753:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1754:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1755:     my (@respids);
1.375     albertel 1756:      my @part_response_id = &flatten_responseType($responseType);
                   1757:     foreach my $part_response_id (@part_response_id) {
                   1758:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1759:         if ($part eq $partid) {
1.375     albertel 1760:             push(@respids,$resp);
1.323     banghart 1761:         }
                   1762:     }
1.318     banghart 1763:     my $result;
1.323     banghart 1764:     foreach my $respid (@respids) {
1.322     albertel 1765: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1766: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1767: 	next if (!@$files);
                   1768: 	my $file_counter = 1;
1.313     banghart 1769: 	foreach my $file (@$files) {
1.368     banghart 1770: 	    if ($file =~ /\/portfolio\//) {
                   1771:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1772:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1773:     	        $file_disp = "$name.$ext";
                   1774:     	        $file = $file_path.$file_disp;
                   1775:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1776:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1777:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1778:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1779:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1780:     	        $file_counter++;
                   1781: 	    }
1.322     albertel 1782: 	}
1.313     banghart 1783:     }
1.318     banghart 1784:     return $result;    
1.71      ng       1785: }
1.44      ng       1786: 
1.58      albertel 1787: sub show_problem {
1.382     albertel 1788:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1789:     my $rendered;
1.382     albertel 1790:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1791:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1792:     if ($mode eq 'both' or $mode eq 'text') {
                   1793: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1794: 						       $env{'request.course.id'},
                   1795: 						       undef,\%form);
1.144     albertel 1796:     }
1.58      albertel 1797:     if ($removeform) {
                   1798: 	$rendered=~s|<form(.*?)>||g;
                   1799: 	$rendered=~s|</form>||g;
1.374     albertel 1800: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1801:     }
1.144     albertel 1802:     my $companswer;
                   1803:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1804: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1805: 	$companswer=
                   1806: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1807: 						    $env{'request.course.id'},
                   1808: 						    %form);
1.144     albertel 1809:     }
1.58      albertel 1810:     if ($removeform) {
                   1811: 	$companswer=~s|<form(.*?)>||g;
                   1812: 	$companswer=~s|</form>||g;
1.144     albertel 1813: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1814:     }
1.468     albertel 1815:     $rendered=
                   1816: 	'<div class="LC_grade_show_problem_header">'.
                   1817: 	&mt('View of the problem').
                   1818: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1819: 	$rendered.
                   1820: 	'</div>';
                   1821:     $companswer=
                   1822: 	'<div class="LC_grade_show_problem_header">'.
                   1823: 	&mt('Correct answer').
                   1824: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1825: 	$companswer.
                   1826: 	'</div>';
                   1827:     my $result;
1.144     albertel 1828:     if ($mode eq 'both') {
1.468     albertel 1829: 	$result=$rendered.$companswer;
1.144     albertel 1830:     } elsif ($mode eq 'text') {
1.468     albertel 1831: 	$result=$rendered;
1.144     albertel 1832:     } elsif ($mode eq 'answer') {
1.468     albertel 1833: 	$result=$companswer;
1.144     albertel 1834:     }
1.468     albertel 1835:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1836:     return $result;
1.58      albertel 1837: }
1.397     albertel 1838: 
1.396     banghart 1839: sub files_exist {
                   1840:     my ($r, $symb) = @_;
                   1841:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1842: 
1.396     banghart 1843:     foreach my $student (@students) {
                   1844:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1845:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1846: 					      $udom,$uname);
1.396     banghart 1847:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1848:         foreach my $submission (@$string) {
                   1849:             my ($partid,$respid) =
                   1850: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1851:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1852: 					   \%record);
                   1853:             return 1 if (@$files);
1.396     banghart 1854:         }
                   1855:     }
1.397     albertel 1856:     return 0;
1.396     banghart 1857: }
1.397     albertel 1858: 
1.394     banghart 1859: sub download_all_link {
                   1860:     my ($r,$symb) = @_;
1.395     albertel 1861:     my $all_students = 
                   1862: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1863: 
                   1864:     my $parts =
                   1865: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1866: 
1.394     banghart 1867:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1868:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1869:                              'cgi.'.$identifier.'.symb' => $symb,
                   1870:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1871:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1872: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1873:     return
                   1874: }
1.395     albertel 1875: 
1.432     banghart 1876: sub build_section_inputs {
                   1877:     my $section_inputs;
                   1878:     if ($env{'form.section'} eq '') {
                   1879:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1880:     } else {
                   1881:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1882:         foreach my $section (@sections) {
1.432     banghart 1883:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1884:         }
                   1885:     }
                   1886:     return $section_inputs;
                   1887: }
                   1888: 
1.44      ng       1889: # --------------------------- show submissions of a student, option to grade 
                   1890: sub submission {
                   1891:     my ($request,$counter,$total) = @_;
1.257     albertel 1892:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1893:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1894:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1895:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1896:     my $symb = &get_symb($request); 
                   1897:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1898: 
                   1899:     if (!&canview($usec)) {
1.398     albertel 1900: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1901: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1902: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1903: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1904: 	return;
                   1905:     }
                   1906: 
1.257     albertel 1907:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1908:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1909:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1910:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1911:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1912: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1913: 	'/check.gif" height="16" border="0" />';
1.41      ng       1914: 
1.426     albertel 1915:     my %old_essays;
1.41      ng       1916:     # header info
                   1917:     if ($counter == 0) {
                   1918: 	&sub_page_js($request);
1.257     albertel 1919: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1920: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1921: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1922: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1923: 	    &download_all_link($request, $symb);
                   1924: 	}
1.485     albertel 1925: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1926: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1927: 
1.44      ng       1928: 	# option to display problem, only once else it cause problems 
                   1929:         # with the form later since the problem has a form.
1.257     albertel 1930: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1931: 	    my $mode;
1.257     albertel 1932: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1933: 		$mode='both';
1.257     albertel 1934: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1935: 		$mode='text';
1.257     albertel 1936: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1937: 		$mode='answer';
                   1938: 	    }
1.329     albertel 1939: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1940: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1941: 	}
1.441     www      1942: 
1.44      ng       1943: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1944:         # if this subroutine has been called once.
1.41      ng       1945: 	my %keyhash = ();
1.257     albertel 1946: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1947: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1948: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1949: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1950: 
1.257     albertel 1951: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1952: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1953: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1954: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1955: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1956: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1957: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1958: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1959: 	}
1.257     albertel 1960: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1961: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1962: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1963: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1964: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1965: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1966: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1967: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1968: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1969: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1970: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1971: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1972: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1973: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1974: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1975: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1976: 			&build_section_inputs().
1.326     albertel 1977: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1978: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1979: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1980: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1981: 	if ($env{'form.handgrade'} eq 'yes') {
                   1982: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1983: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1984: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1985: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1986: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1987: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1988: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1989: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1990: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1991: 	    }
1.123     ng       1992: 	}
1.41      ng       1993: 	
                   1994: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1995: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1996: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1997: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1998: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1999: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2000: 		'" />'."\n".
                   2001: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2002: 	    $cts++;
                   2003: 	}
                   2004: 	$request->print($prnmsg);
1.32      ng       2005: 
1.257     albertel 2006: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2007: #
                   2008: # Print out the keyword options line
                   2009: #
1.41      ng       2010: 	    $request->print(<<KEYWORDS);
1.38      ng       2011: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2012: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       2013: <a href="#" onMouseDown="javascript:getSel(); return false"
                   2014:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2015: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2016: KEYWORDS
1.88      www      2017: #
                   2018: # Load the other essays for similarity check
                   2019: #
1.324     albertel 2020:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2021: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2022: 	    $apath=&escape($apath);
1.88      www      2023: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2024: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2025:         }
                   2026:     }
1.44      ng       2027: 
1.441     www      2028: # This is where output for one specific student would start
1.468     albertel 2029:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2030:     $request->print("\n\n".
1.468     albertel 2031:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2032: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2033: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2034: 
1.257     albertel 2035:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2036: 	my $mode;
1.257     albertel 2037: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2038: 	    $mode='both';
1.257     albertel 2039: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2040: 	    $mode='text';
1.257     albertel 2041: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2042: 	    $mode='answer';
                   2043: 	}
1.329     albertel 2044: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2045: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2046:     }
1.144     albertel 2047: 
1.257     albertel 2048:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2049:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2050: 
1.44      ng       2051:     # Display student info
1.41      ng       2052:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2053:     my $result='<div class="LC_grade_submissions">';
                   2054:     
                   2055:     $result.='<div class="LC_grade_submissions_header">';
                   2056:     $result.= &mt('Submissions');
1.45      ng       2057:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2058: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2059:     if ($env{'form.handgrade'} eq 'no') {
                   2060: 	$result.='<span class="LC_grade_check_note">'.
                   2061: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2062: 
                   2063:     }
                   2064: 
                   2065: 
1.41      ng       2066: 
1.118     ng       2067:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2068:     my $fullname;
                   2069:     my $col_fullnames = [];
1.257     albertel 2070:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2071: 	(my $sub_result,$fullname,$col_fullnames)=
                   2072: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2073: 				 $counter);
                   2074: 	$result.=$sub_result;
1.41      ng       2075:     }
1.44      ng       2076:     $request->print($result."\n");
1.468     albertel 2077:     $request->print('</div>'."\n");
1.44      ng       2078:     # print student answer/submission
                   2079:     # Options are (1) Handgaded submission only
                   2080:     #             (2) Last submission, includes submission that is not handgraded 
                   2081:     #                  (for multi-response type part)
                   2082:     #             (3) Last submission plus the parts info
                   2083:     #             (4) The whole record for this student
1.257     albertel 2084:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2085: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2086: 	
                   2087: 	my $lastsubonly;
                   2088: 
1.151     albertel 2089: 	if ($$timestamp eq '') {
1.468     albertel 2090: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2091: 	} else {
1.468     albertel 2092: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2093: 
1.151     albertel 2094: 	    my %seenparts;
1.375     albertel 2095: 	    my @part_response_id = &flatten_responseType($responseType);
                   2096: 	    foreach my $part (@part_response_id) {
1.393     albertel 2097: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2098: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2099: 
1.375     albertel 2100: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2101: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2102: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2103: 		    if (exists($seenparts{$partid})) { next; }
                   2104: 		    $seenparts{$partid}=1;
1.207     albertel 2105: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2106: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2107: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2108: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2109: 			'\');" target="_self">'.
1.257     albertel 2110: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2111: 		    $request->print($submitby);
                   2112: 		    next;
                   2113: 		}
                   2114: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2115: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2116: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2117: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2118: 			' )</span>&nbsp; &nbsp;'.
1.539     riegler  2119: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2120: 		    next;
                   2121: 		}
1.468     albertel 2122: 		foreach my $submission (@$string) {
                   2123: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2124: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2125: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2126: 		    # Similarity check
                   2127: 		    my $similar='';
1.257     albertel 2128: 		    if($env{'form.checkPlag'}){
1.151     albertel 2129: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2130: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2131: 			if ($osim) {
                   2132: 			    $osim=int($osim*100.0);
1.426     albertel 2133: 			    my %old_course_desc = 
                   2134: 				&Apache::lonnet::coursedescription($ocrsid,
                   2135: 								   {'one_time' => 1});
                   2136: 
                   2137: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.574     bisitz   2138: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
1.426     albertel 2139: 				    $osim,
1.574     bisitz   2140: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.426     albertel 2141: 				    $old_course_desc{'description'},
1.427     albertel 2142: 				    $old_course_desc{'num'},
1.426     albertel 2143: 				    $old_course_desc{'domain'}).
1.398     albertel 2144: 				'</span></h3><blockquote><i>'.
1.151     albertel 2145: 				&keywords_highlight($oessay).
                   2146: 				'</i></blockquote><hr />';
                   2147: 			}
1.150     albertel 2148: 		    }
1.151     albertel 2149: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2150: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2151: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2152: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2153: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2154: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2155: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2156: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2157: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2158: 			if (@$files) {
1.544     raeburn  2159: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
1.303     banghart 2160: 			    my $file_counter = 0;
1.313     banghart 2161: 			    foreach my $file (@$files) {
1.468     albertel 2162: 			        $file_counter++;
1.232     albertel 2163: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.564     bisitz   2164: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
1.232     albertel 2165: 			    }
1.236     albertel 2166: 			    $lastsubonly.='<br />';
1.41      ng       2167: 			}
1.468     albertel 2168: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2169: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
1.555     raeburn  2170: 					 $respid,\%record,$order,undef,$uname,$udom);
1.151     albertel 2171: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2172: 			$lastsubonly.='</div>';
1.41      ng       2173: 		    }
                   2174: 		}
                   2175: 	    }
1.468     albertel 2176: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2177: 	}
                   2178: 	$request->print($lastsubonly);
1.468     albertel 2179:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2180: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2181: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2182:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2183: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2184: 								 $env{'request.course.id'},
1.44      ng       2185: 								 $last,'.submission',
                   2186: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2187:     }
1.120     ng       2188: 
1.121     ng       2189:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2190: 	.$udom.'" />'."\n");
1.44      ng       2191:     # return if view submission with no grading option
1.257     albertel 2192:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2193: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2194: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2195: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2196: 	$toGrade.='</div>'."\n";
1.257     albertel 2197: 	if (($env{'form.command'} eq 'submission') || 
                   2198: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2199: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2200: 	}
1.180     albertel 2201: 	$request->print($toGrade);
1.41      ng       2202: 	return;
1.180     albertel 2203:     } else {
1.468     albertel 2204: 	$request->print('</div>'."\n");
1.41      ng       2205:     }
1.33      ng       2206: 
1.121     ng       2207:     # essay grading message center
1.257     albertel 2208:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2209: 	my $result='<div class="LC_grade_message_center">';
                   2210:     
                   2211: 	$result.='<div class="LC_grade_message_center_header">'.
                   2212: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2213: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2214: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2215: 	if (scalar(@$col_fullnames) > 0) {
                   2216: 	    my $lastone = pop(@$col_fullnames);
                   2217: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2218: 	}
                   2219: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2220: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2221: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2222: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2223: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2224: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2225: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2226: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2227: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2228: 	    '<br />&nbsp;('.
1.468     albertel 2229: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2230: 	$result.='</div></div>';
1.121     ng       2231: 	$request->print($result);
1.118     ng       2232:     }
1.41      ng       2233: 
                   2234:     my %seen = ();
                   2235:     my @partlist;
1.129     ng       2236:     my @gradePartRespid;
1.375     albertel 2237:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2238:     $request->print('<div class="LC_grade_assign">'.
                   2239: 		    
                   2240: 		    '<div class="LC_grade_assign_header">'.
                   2241: 		    &mt('Assign Grades').'</div>'.
                   2242: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2243:     foreach my $part_response_id (@part_response_id) {
                   2244:     	my ($partid,$respid) = @{ $part_response_id };
                   2245: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2246: 	next if ($seen{$partid} > 0);
1.41      ng       2247: 	$seen{$partid}++;
1.393     albertel 2248: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2249: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2250: 	push(@partlist,$partid);
                   2251: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2252: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2253:     }
1.468     albertel 2254:     $request->print('</div></div>');
                   2255: 
                   2256:     $request->print('<div class="LC_grade_info_links">');
                   2257:     if ($perm{'vgr'}) {
                   2258: 	$request->print(
                   2259: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2260: 						   $uname,$udom,'check'));
                   2261:     }
                   2262:     if ($perm{'opa'}) {
                   2263: 	$request->print(
                   2264: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2265: 					 $uname,$udom,$symb,'check'));
                   2266:     }
                   2267:     $request->print('</div>');
                   2268: 
1.45      ng       2269:     $result='<input type="hidden" name="partlist'.$counter.
                   2270: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2271:     $result.='<input type="hidden" name="gradePartRespid'.
                   2272: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2273:     my $ctr = 0;
                   2274:     while ($ctr < scalar(@partlist)) {
                   2275: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2276: 	    $partlist[$ctr].'" />'."\n";
                   2277: 	$ctr++;
                   2278:     }
1.468     albertel 2279:     $request->print($result.''."\n");
1.41      ng       2280: 
1.441     www      2281: # Done with printing info for one student
                   2282: 
1.468     albertel 2283:     $request->print('</div>');#LC_grade_show_user_body
                   2284:     $request->print('</div>');#LC_grade_show_user
1.441     www      2285: 
                   2286: 
1.41      ng       2287:     # print end of form
                   2288:     if ($counter == $total) {
1.297     www      2289: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2290: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2291: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2292: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2293: 	my $ntstu ='<select name="NTSTU">'.
                   2294: 	    '<option>1</option><option>2</option>'.
                   2295: 	    '<option>3</option><option>5</option>'.
                   2296: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2297: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2298: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.549     hauer    2299: 	$endform.=&mt('[quant,_1,student]',$ntstu);
1.485     albertel 2300: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2301: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2302: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2303: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2304: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2305:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2306:             "' name='increment' />";
1.485     albertel 2307: 	$endform.='</td></tr></table></form>';
1.324     albertel 2308: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2309: 	$request->print($endform);
                   2310:     }
                   2311:     return '';
1.38      ng       2312: }
                   2313: 
1.464     albertel 2314: sub check_collaborators {
                   2315:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2316:     my ($result,@col_fullnames);
                   2317:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2318:     foreach my $part (keys(%$handgrade)) {
                   2319: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2320: 					'.maxcollaborators',
                   2321: 					$symb,$udom,$uname);
                   2322: 	next if ($ncol <= 0);
                   2323: 	$part =~ s/\_/\./g;
                   2324: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2325: 	my (@good_collaborators, @bad_collaborators);
                   2326: 	foreach my $possible_collaborator
                   2327: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2328: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2329: 	    next if ($possible_collaborator eq '');
                   2330: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2331: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2332: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2333: 	    # Doing this grep allows 'fuzzy' specification
                   2334: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2335: 			       keys(%$classlist));
                   2336: 	    if (! scalar(@matches)) {
                   2337: 		push(@bad_collaborators, $possible_collaborator);
                   2338: 	    } else {
                   2339: 		push(@good_collaborators, @matches);
                   2340: 	    }
                   2341: 	}
                   2342: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2343: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2344: 	    foreach my $name (@good_collaborators) {
                   2345: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2346: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2347: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2348: 	    }
                   2349: 	    $result.='<br />'."\n";
1.466     albertel 2350: 	    my ($part)=split(/\./,$part);
1.464     albertel 2351: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2352: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2353: 		"\n";
                   2354: 	}
                   2355: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2356: 	    $result.='<div class="LC_warning">';
1.464     albertel 2357: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2358: 	    $result .= '</div>';
                   2359: 	}         
                   2360: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2361: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2362: 	    $result .= &mt('This student has submitted too many '.
                   2363: 		'collaborators.  Maximum is [_1].',$ncol);
                   2364: 	    $result .= '</div>';
                   2365: 	}
                   2366:     }
                   2367:     return ($result,$fullname,\@col_fullnames);
                   2368: }
                   2369: 
1.44      ng       2370: #--- Retrieve the last submission for all the parts
1.38      ng       2371: sub get_last_submission {
1.119     ng       2372:     my ($returnhash)=@_;
1.46      ng       2373:     my (@string,$timestamp);
1.119     ng       2374:     if ($$returnhash{'version'}) {
1.46      ng       2375: 	my %lasthash=();
                   2376: 	my ($version);
1.119     ng       2377: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2378: 	    foreach my $key (sort(split(/\:/,
                   2379: 					$$returnhash{$version.':keys'}))) {
                   2380: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2381: 		$timestamp = 
1.545     raeburn  2382: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2383: 	    }
                   2384: 	}
1.397     albertel 2385: 	foreach my $key (keys(%lasthash)) {
                   2386: 	    next if ($key !~ /\.submission$/);
                   2387: 
                   2388: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2389: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2390: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2391: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2392: 	}
                   2393:     }
1.397     albertel 2394:     if (!@string) {
                   2395: 	$string[0] =
1.539     riegler  2396: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2397:     }
                   2398:     return (\@string,\$timestamp);
1.38      ng       2399: }
1.35      ng       2400: 
1.44      ng       2401: #--- High light keywords, with style choosen by user.
1.38      ng       2402: sub keywords_highlight {
1.44      ng       2403:     my $string    = shift;
1.257     albertel 2404:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2405:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2406:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2407:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2408:     foreach my $keyword (@keylist) {
                   2409: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2410:     }
                   2411:     return $string;
1.38      ng       2412: }
1.36      ng       2413: 
1.44      ng       2414: #--- Called from submission routine
1.38      ng       2415: sub processHandGrade {
1.41      ng       2416:     my ($request) = shift;
1.324     albertel 2417:     my $symb   = &get_symb($request);
                   2418:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2419:     my $button = $env{'form.gradeOpt'};
                   2420:     my $ngrade = $env{'form.NCT'};
                   2421:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2422:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2423:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2424: 
1.44      ng       2425:     if ($button eq 'Save & Next') {
                   2426: 	my $ctr = 0;
                   2427: 	while ($ctr < $ngrade) {
1.257     albertel 2428: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2429: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2430: 	    if ($errorflag eq 'no_score') {
                   2431: 		$ctr++;
                   2432: 		next;
                   2433: 	    }
1.104     albertel 2434: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2435: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2436: 		$ctr++;
                   2437: 		next;
                   2438: 	    }
1.257     albertel 2439: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2440: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2441: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2442:             my ($feedurl,$showsymb) =
                   2443: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2444: 	    my $messagetail;
1.62      albertel 2445: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2446: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2447: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2448: 		$subject.=' ['.$restitle.']';
1.44      ng       2449: 		my (@msgnum) = split(/,/,$includemsg);
                   2450: 		foreach (@msgnum) {
1.257     albertel 2451: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2452: 		}
1.80      ng       2453: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2454: 		if ($env{'form.withgrades'.$ctr}) {
                   2455: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2456: 		    $messagetail = " for <a href=\"".
1.418     albertel 2457: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2458: 		}
                   2459: 		$msgstatus = 
                   2460:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2461: 						     $message.$messagetail,
1.418     albertel 2462:                                                      undef,$feedurl,undef,
1.386     raeburn  2463:                                                      undef,undef,$showsymb,
                   2464:                                                      $restitle);
1.574     bisitz   2465: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2466: 				$msgstatus);
1.44      ng       2467: 	    }
1.257     albertel 2468: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2469: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2470: 		foreach my $collabstr (@collabstrs) {
                   2471: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2472: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2473: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2474: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2475: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2476: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2477: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2478: 			    next;
1.418     albertel 2479: 			} elsif ($message ne '') {
                   2480: 			    my ($baseurl,$showsymb) = 
                   2481: 				&get_feedurl_and_symb($symb,$collaborator,
                   2482: 						      $udom);
                   2483: 			    if ($env{'form.withgrades'.$ctr}) {
                   2484: 				$messagetail = " for <a href=\"".
1.386     raeburn  2485:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2486: 			    }
1.418     albertel 2487: 			    $msgstatus = 
                   2488: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2489: 			}
1.44      ng       2490: 		    }
                   2491: 		}
                   2492: 	    }
                   2493: 	    $ctr++;
                   2494: 	}
                   2495:     }
                   2496: 
1.257     albertel 2497:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2498: 	# Keywords sorted in alphabatical order
1.257     albertel 2499: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2500: 	my %keyhash = ();
1.257     albertel 2501: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2502: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2503: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2504: 	$env{'form.keywords'} = join(' ',@keywords);
                   2505: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2506: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2507: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2508: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2509: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2510: 
                   2511: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2512: 	# New messages are saved in env for the next student.
1.119     ng       2513: 	# All messages are saved in nohist_handgrade.db
                   2514: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2515: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2516: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2517: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2518: 		$idx++;
                   2519: 	    }
                   2520: 	    $ctr++;
1.41      ng       2521: 	}
1.119     ng       2522: 	$ctr = 0;
                   2523: 	while ($ctr < $ngrade) {
1.257     albertel 2524: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2525: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2526: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2527: 		$idx++;
                   2528: 	    }
                   2529: 	    $ctr++;
1.41      ng       2530: 	}
1.257     albertel 2531: 	$env{'form.savemsgN'} = --$idx;
                   2532: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2533: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2534: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2535:     }
1.44      ng       2536:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2537:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2538:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2539: 	my ($ctr,$total) = (0,0);
                   2540: 	while ($ctr < $ngrade) {
1.257     albertel 2541: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2542: 	    $ctr++;
                   2543: 	}
1.257     albertel 2544: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2545: 	$ctr = 0;
                   2546: 	while ($ctr < $total) {
1.257     albertel 2547: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2548: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2549: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2550: 	    &submission($request,$ctr,$total-1);
1.41      ng       2551: 	    $ctr++;
                   2552: 	}
                   2553: 	return '';
                   2554:     }
1.36      ng       2555: 
1.121     ng       2556: # Go directly to grade student - from submission or link from chart page
1.120     ng       2557:     if ($button eq 'Grade Student') {
1.324     albertel 2558: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2559: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2560: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2561: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2562: 	&submission($request,0,0);
                   2563: 	return '';
                   2564:     }
                   2565: 
1.44      ng       2566:     # Get the next/previous one or group of students
1.257     albertel 2567:     my $firststu = $env{'form.unamedom0'};
                   2568:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2569:     my $ctr = 2;
1.41      ng       2570:     while ($laststu eq '') {
1.257     albertel 2571: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2572: 	$ctr++;
                   2573: 	$laststu = $firststu if ($ctr > $ngrade);
                   2574:     }
1.44      ng       2575: 
1.41      ng       2576:     my (@parsedlist,@nextlist);
                   2577:     my ($nextflg) = 0;
1.524     raeburn  2578:     foreach my $item (sort 
1.294     albertel 2579: 	     {
                   2580: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2581: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2582: 		 }
                   2583: 		 return $a cmp $b;
                   2584: 	     } (keys(%$fullname))) {
1.41      ng       2585: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2586: 	    push(@parsedlist,$item);
1.41      ng       2587: 	}
1.524     raeburn  2588: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2589: 	if ($button eq 'Previous') {
1.524     raeburn  2590: 	    last if ($item eq $firststu);
                   2591: 	    push(@parsedlist,$item);
1.41      ng       2592: 	}
                   2593:     }
                   2594:     $ctr = 0;
                   2595:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2596:     my ($partlist) = &response_type($symb);
1.41      ng       2597:     foreach my $student (@parsedlist) {
1.257     albertel 2598: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2599: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2600: 	
                   2601: 	if ($submitonly eq 'queued') {
                   2602: 	    my %queue_status = 
                   2603: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2604: 							$udom,$uname);
                   2605: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2606: 	}
                   2607: 
1.156     albertel 2608: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2609: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2610: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2611: 	    my $submitted = 0;
1.248     albertel 2612: 	    my $ungraded = 0;
                   2613: 	    my $incorrect = 0;
1.524     raeburn  2614: 	    foreach my $item (keys(%status)) {
                   2615: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2616: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2617: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2618: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2619: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2620: 		    $submitted = 0;
                   2621: 		}
1.41      ng       2622: 	    }
1.156     albertel 2623: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2624: 				     $submitonly eq 'incorrect' ||
                   2625: 				     $submitonly eq 'graded'));
1.248     albertel 2626: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2627: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2628: 	}
1.524     raeburn  2629: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2630: 	last if ($ctr == $ntstu);
1.41      ng       2631: 	$ctr++;
                   2632:     }
1.36      ng       2633: 
1.41      ng       2634:     $ctr = 0;
                   2635:     my $total = scalar(@nextlist)-1;
1.39      ng       2636: 
1.524     raeburn  2637:     foreach (sort(@nextlist)) {
1.41      ng       2638: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2639: 	$env{'form.student'}  = $uname;
                   2640: 	$env{'form.userdom'}  = $udom;
                   2641: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2642: 	&submission($request,$ctr,$total);
                   2643: 	$ctr++;
                   2644:     }
                   2645:     if ($total < 0) {
1.485     albertel 2646: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2647: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2648: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2649: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2650: 	$request->print($the_end);
                   2651:     }
                   2652:     return '';
1.38      ng       2653: }
1.36      ng       2654: 
1.44      ng       2655: #---- Save the score and award for each student, if changed
1.38      ng       2656: sub saveHandGrade {
1.324     albertel 2657:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2658:     my @version_parts;
1.104     albertel 2659:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2660: 					   $env{'request.course.id'});
1.104     albertel 2661:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2662:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2663:     my @parts_graded;
1.77      ng       2664:     my %newrecord  = ();
                   2665:     my ($pts,$wgt) = ('','');
1.269     raeburn  2666:     my %aggregate = ();
                   2667:     my $aggregateflag = 0;
1.301     albertel 2668:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2669:     foreach my $new_part (@parts) {
1.337     banghart 2670: 	#collaborator ($submi may vary for different parts
1.259     banghart 2671: 	if ($submitter && $new_part ne $part) { next; }
                   2672: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2673: 	if ($dropMenu eq 'excused') {
1.259     banghart 2674: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2675: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2676: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2677: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2678: 		}
1.364     banghart 2679: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2680: 	    }
1.125     ng       2681: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2682: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2683: 	    foreach my $key (keys(%record)) {
1.259     banghart 2684: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2685: 	    }
1.259     banghart 2686: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2687: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2688:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2689: 
                   2690:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2691: 					       [$new_part]);
                   2692:             my $aggtries =$totaltries;
1.269     raeburn  2693:             if ($last_resets{$new_part}) {
1.270     albertel 2694:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2695: 					   $new_part);
1.269     raeburn  2696:             }
1.270     albertel 2697: 
                   2698:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2699:             if ($aggtries > 0) {
1.327     albertel 2700:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2701:                 $aggregateflag = 1;
                   2702:             }
1.125     ng       2703: 	} elsif ($dropMenu eq '') {
1.259     banghart 2704: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2705: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2706: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2707: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2708: 		next;
                   2709: 	    }
1.259     banghart 2710: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2711: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2712: 	    my $partial= $pts/$wgt;
1.259     banghart 2713: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2714: 		#do not update score for part if not changed.
1.346     banghart 2715:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2716: 		next;
1.251     banghart 2717: 	    } else {
1.524     raeburn  2718: 	        push(@parts_graded,$new_part);
1.153     albertel 2719: 	    }
1.259     banghart 2720: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2721: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2722: 	    }
1.259     banghart 2723: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2724: 	    if ($partial == 0) {
1.153     albertel 2725: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2726: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2727: 		}
1.41      ng       2728: 	    } else {
1.153     albertel 2729: 		if ($record{$reckey} ne 'correct_by_override') {
                   2730: 		    $newrecord{$reckey} = 'correct_by_override';
                   2731: 		}
                   2732: 	    }	    
                   2733: 	    if ($submitter && 
1.259     banghart 2734: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2735: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2736: 	    }
1.259     banghart 2737: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2738: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2739: 	}
1.259     banghart 2740: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2741: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2742: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2743: 	        $dropMenu eq 'reset status')
                   2744: 	   {
1.524     raeburn  2745: 	    push(@version_parts,$new_part);
1.259     banghart 2746: 	}
1.41      ng       2747:     }
1.301     albertel 2748:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2749:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2750: 
1.344     albertel 2751:     if (%newrecord) {
                   2752:         if (@version_parts) {
1.364     banghart 2753:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2754:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2755: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2756: 	    foreach my $new_part (@version_parts) {
                   2757: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2758: 				$new_part,\%newrecord);
                   2759: 	    }
1.259     banghart 2760:         }
1.44      ng       2761: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2762: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2763: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2764: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2765:     }
1.269     raeburn  2766:     if ($aggregateflag) {
                   2767:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2768: 			      $cdom,$cnum);
1.269     raeburn  2769:     }
1.301     albertel 2770:     return ('',$pts,$wgt);
1.36      ng       2771: }
1.322     albertel 2772: 
1.380     albertel 2773: sub check_and_remove_from_queue {
                   2774:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2775:     my @ungraded_parts;
                   2776:     foreach my $part (@{$parts}) {
                   2777: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2778: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2779: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2780: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2781: 		) {
                   2782: 	    push(@ungraded_parts, $part);
                   2783: 	}
                   2784:     }
                   2785:     if ( !@ungraded_parts ) {
                   2786: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2787: 					       $cnum,$domain,$stuname);
                   2788:     }
                   2789: }
                   2790: 
1.337     banghart 2791: sub handback_files {
                   2792:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2793:     my $portfolio_root = '/userfiles/portfolio';
1.359     www      2794:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2795: 
                   2796:     my @part_response_id = &flatten_responseType($responseType);
                   2797:     foreach my $part_response_id (@part_response_id) {
                   2798:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2799: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2800:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2801:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2802:                 my $file_counter = 1;
1.367     albertel 2803: 		my $file_msg;
1.337     banghart 2804:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2805:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2806:                     my ($directory,$answer_file) = 
                   2807:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2808:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2809: 		        &file_name_version_ext($answer_file);
1.355     banghart 2810: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2811:                     my $getpropath = 1;
                   2812: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2813: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2814:                     # fix file name
                   2815:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2816:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2817:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2818:             	                                $save_file_name);
1.337     banghart 2819:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2820:                         $request->print('<br /><span class="LC_error">'.
                   2821:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2822:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2823:                                         '</span>');
1.356     banghart 2824:                     } else {
1.360     banghart 2825:                         # mark the file as read only
                   2826:                         my @files = ($save_file_name);
1.372     albertel 2827:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2828:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2829: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2830: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2831: 			}
                   2832:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2833: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2834: 
1.337     banghart 2835:                     }
                   2836:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2837:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2838:                     $file_counter++;
                   2839:                 }
1.367     albertel 2840: 		my $subject = "File Handed Back by Instructor ";
                   2841: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2842: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2843: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2844: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2845: 		my ($feedurl,$showsymb) = 
                   2846: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2847:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2848: 		my $msgstatus = 
                   2849:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2850: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2851:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2852:             }
                   2853:         }
1.338     banghart 2854:     return;
1.337     banghart 2855: }
                   2856: 
1.418     albertel 2857: sub get_feedurl_and_symb {
                   2858:     my ($symb,$uname,$udom) = @_;
                   2859:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2860:     $url = &Apache::lonnet::clutter($url);
                   2861:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2862: 					$symb,$udom,$uname);
                   2863:     if ($encrypturl =~ /^yes$/i) {
                   2864: 	&Apache::lonenc::encrypted(\$url,1);
                   2865: 	&Apache::lonenc::encrypted(\$symb,1);
                   2866:     }
                   2867:     return ($url,$symb);
                   2868: }
                   2869: 
1.313     banghart 2870: sub get_submitted_files {
                   2871:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2872:     my @files;
                   2873:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2874:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2875:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2876:     	    push(@files,$file_url.$file);
                   2877:         }
                   2878:     }
                   2879:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2880:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2881:     }
                   2882:     return (\@files);
                   2883: }
1.322     albertel 2884: 
1.269     raeburn  2885: # ----------- Provides number of tries since last reset.
                   2886: sub get_num_tries {
                   2887:     my ($record,$last_reset,$part) = @_;
                   2888:     my $timestamp = '';
                   2889:     my $num_tries = 0;
                   2890:     if ($$record{'version'}) {
                   2891:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2892:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2893:                 $timestamp = $$record{$version.':timestamp'};
                   2894:                 if ($timestamp > $last_reset) {
                   2895:                     $num_tries ++;
                   2896:                 } else {
                   2897:                     last;
                   2898:                 }
                   2899:             }
                   2900:         }
                   2901:     }
                   2902:     return $num_tries;
                   2903: }
                   2904: 
                   2905: # ----------- Determine decrements required in aggregate totals 
                   2906: sub decrement_aggs {
                   2907:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2908:     my %decrement = (
                   2909:                         attempts => 0,
                   2910:                         users => 0,
                   2911:                         correct => 0
                   2912:                     );
                   2913:     $decrement{'attempts'} = $aggtries;
                   2914:     if ($solvedstatus =~ /^correct/) {
                   2915:         $decrement{'correct'} = 1;
                   2916:     }
                   2917:     if ($aggtries == $totaltries) {
                   2918:         $decrement{'users'} = 1;
                   2919:     }
1.524     raeburn  2920:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2921:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2922:     }
                   2923:     return;
                   2924: }
                   2925: 
                   2926: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2927: sub get_last_resets {
1.270     albertel 2928:     my ($symb,$courseid,$partids) =@_;
                   2929:     my %last_resets;
1.269     raeburn  2930:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2931:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2932:     my @keys;
                   2933:     foreach my $part (@{$partids}) {
                   2934: 	push(@keys,"$symb\0$part\0resettime");
                   2935:     }
                   2936:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2937: 				     $cdom,$cname);
                   2938:     foreach my $part (@{$partids}) {
                   2939: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2940:     }
1.270     albertel 2941:     return %last_resets;
1.269     raeburn  2942: }
                   2943: 
1.251     banghart 2944: # ----------- Handles creating versions for portfolio files as answers
                   2945: sub version_portfiles {
1.343     banghart 2946:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2947:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2948:     my @returned_keys;
1.255     banghart 2949:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2950:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2951:     foreach my $key (keys(%$record)) {
1.259     banghart 2952:         my $new_portfiles;
1.263     banghart 2953:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2954:             my @versioned_portfiles;
1.367     albertel 2955:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2956:             foreach my $file (@portfiles) {
1.306     banghart 2957:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2958:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2959: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2960: 		    &file_name_version_ext($answer_file);
1.517     raeburn  2961:                 my $getpropath = 1;    
                   2962:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 2963:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2964:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2965:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2966:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2967:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2968:                         [$directory.$new_answer],
1.306     banghart 2969:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2970:                 }
1.252     banghart 2971:             }
1.343     banghart 2972:             $$record{$key} = join(',',@versioned_portfiles);
                   2973:             push(@returned_keys,$key);
1.251     banghart 2974:         }
                   2975:     } 
1.343     banghart 2976:     return (@returned_keys);   
1.305     banghart 2977: }
                   2978: 
1.307     banghart 2979: sub get_next_version {
1.341     banghart 2980:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2981:     my $version;
                   2982:     foreach my $row (@$dir_list) {
                   2983:         my ($file) = split(/\&/,$row,2);
                   2984:         my ($file_name,$file_version,$file_ext) =
                   2985: 	    &file_name_version_ext($file);
                   2986:         if (($file_name eq $answer_name) && 
                   2987: 	    ($file_ext eq $answer_ext)) {
                   2988:                 # gets here if filename and extension match, regardless of version
                   2989:                 if ($file_version ne '') {
                   2990:                 # a versioned file is found  so save it for later
                   2991:                 if ($file_version > $version) {
                   2992: 		    $version = $file_version;
                   2993: 	        }
                   2994:             }
                   2995:         }
                   2996:     } 
                   2997:     $version ++;
                   2998:     return($version);
                   2999: }
                   3000: 
1.305     banghart 3001: sub version_selected_portfile {
1.306     banghart 3002:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3003:     my ($answer_name,$answer_ver,$answer_ext) =
                   3004:         &file_name_version_ext($file_name);
                   3005:     my $new_answer;
                   3006:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3007:     if($env{'form.copy'} eq '-1') {
                   3008:         $new_answer = 'problem getting file';
                   3009:     } else {
                   3010:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3011:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3012:                             $stu_name,$domain,'copy',
                   3013: 		        '/portfolio'.$directory.$new_answer);
                   3014:     }    
                   3015:     return ($new_answer);
1.251     banghart 3016: }
                   3017: 
1.304     albertel 3018: sub file_name_version_ext {
                   3019:     my ($file)=@_;
                   3020:     my @file_parts = split(/\./, $file);
                   3021:     my ($name,$version,$ext);
                   3022:     if (@file_parts > 1) {
                   3023: 	$ext=pop(@file_parts);
                   3024: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3025: 	    $version=pop(@file_parts);
                   3026: 	}
                   3027: 	$name=join('.',@file_parts);
                   3028:     } else {
                   3029: 	$name=join('.',@file_parts);
                   3030:     }
                   3031:     return($name,$version,$ext);
                   3032: }
                   3033: 
1.44      ng       3034: #--------------------------------------------------------------------------------------
                   3035: #
                   3036: #-------------------------- Next few routines handles grading by section or whole class
                   3037: #
                   3038: #--- Javascript to handle grading by section or whole class
1.42      ng       3039: sub viewgrades_js {
                   3040:     my ($request) = shift;
                   3041: 
1.539     riegler  3042:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3043:     $request->print(<<VIEWJAVASCRIPT);
                   3044: <script type="text/javascript" language="javascript">
1.45      ng       3045:    function writePoint(partid,weight,point) {
1.125     ng       3046: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3047: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3048: 	if (point == "textval") {
1.125     ng       3049: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3050: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3051: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3052: 		var resetbox = false;
                   3053: 		for (var i=0; i<radioButton.length; i++) {
                   3054: 		    if (radioButton[i].checked) {
                   3055: 			textbox.value = i;
                   3056: 			resetbox = true;
                   3057: 		    }
                   3058: 		}
                   3059: 		if (!resetbox) {
                   3060: 		    textbox.value = "";
                   3061: 		}
                   3062: 		return;
                   3063: 	    }
1.109     matthew  3064: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3065: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3066: 				   ") greater than the weight for the part. Accept?");
                   3067: 		if (resp == false) {
                   3068: 		    textbox.value = "";
                   3069: 		    return;
                   3070: 		}
                   3071: 	    }
1.42      ng       3072: 	    for (var i=0; i<radioButton.length; i++) {
                   3073: 		radioButton[i].checked=false;
1.109     matthew  3074: 		if (parseFloat(point) == i) {
1.42      ng       3075: 		    radioButton[i].checked=true;
                   3076: 		}
                   3077: 	    }
1.41      ng       3078: 
1.42      ng       3079: 	} else {
1.125     ng       3080: 	    textbox.value = parseFloat(point);
1.42      ng       3081: 	}
1.41      ng       3082: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3083: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3084: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3085: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3086: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3087: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3088: 	    if (saveval != "correct") {
                   3089: 		scorename.value = point;
1.43      ng       3090: 		if (selname[0].selected != true) {
                   3091: 		    selname[0].selected = true;
                   3092: 		}
1.42      ng       3093: 	    }
                   3094: 	}
1.125     ng       3095: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3096:     }
                   3097: 
                   3098:     function writeRadText(partid,weight) {
1.125     ng       3099: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3100: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3101:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3102: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3103: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3104: 	    for (var i=0; i<radioButton.length; i++) {
                   3105: 		radioButton[i].checked=false;
                   3106: 
                   3107: 	    }
                   3108: 	    textbox.value = "";
                   3109: 
                   3110: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3111: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3112: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3113: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3114: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3115: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3116: 		if ((saveval != "correct") || override) {
1.42      ng       3117: 		    scorename.value = "";
1.125     ng       3118: 		    if (selval[1].selected) {
                   3119: 			selname[1].selected = true;
                   3120: 		    } else {
                   3121: 			selname[2].selected = true;
                   3122: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3123: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3124: 		    }
1.42      ng       3125: 		}
                   3126: 	    }
1.43      ng       3127: 	} else {
                   3128: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3129: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3130: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3131: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3132: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3133: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3134: 		if ((saveval != "correct") || override) {
1.125     ng       3135: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3136: 		    selname[0].selected = true;
                   3137: 		}
                   3138: 	    }
                   3139: 	}	    
1.42      ng       3140:     }
                   3141: 
                   3142:     function changeSelect(partid,user) {
1.125     ng       3143: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3144: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3145: 	var point  = textbox.value;
1.125     ng       3146: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3147: 
1.109     matthew  3148: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3149: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3150: 	    textbox.value = "";
                   3151: 	    return;
                   3152: 	}
1.109     matthew  3153: 	if (parseFloat(point) > parseFloat(weight)) {
                   3154: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3155: 			       ") greater than the weight of the part. Accept?");
                   3156: 	    if (resp == false) {
                   3157: 		textbox.value = "";
                   3158: 		return;
                   3159: 	    }
                   3160: 	}
1.42      ng       3161: 	selval[0].selected = true;
                   3162:     }
                   3163: 
                   3164:     function changeOneScore(partid,user) {
1.125     ng       3165: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3166: 	if (selval[1].selected || selval[2].selected) {
                   3167: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3168: 	    if (selval[2].selected) {
                   3169: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3170: 	    }
1.269     raeburn  3171:         }
1.42      ng       3172:     }
                   3173: 
                   3174:     function resetEntry(numpart) {
                   3175: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3176: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3177: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3178: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3179: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3180: 	    for (var i=0; i<radioButton.length; i++) {
                   3181: 		radioButton[i].checked=false;
                   3182: 
                   3183: 	    }
                   3184: 	    textbox.value = "";
                   3185: 	    selval[0].selected = true;
                   3186: 
                   3187: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3188: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3189: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3190: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3191: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3192: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3193: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3194: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3195: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3196: 		if (saveselval == "excused") {
1.43      ng       3197: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3198: 		} else {
1.43      ng       3199: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3200: 		}
                   3201: 	    }
1.41      ng       3202: 	}
1.42      ng       3203:     }
                   3204: 
1.41      ng       3205: </script>
                   3206: VIEWJAVASCRIPT
1.42      ng       3207: }
                   3208: 
1.44      ng       3209: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3210: sub viewgrades {
                   3211:     my ($request) = shift;
                   3212:     &viewgrades_js($request);
1.41      ng       3213: 
1.324     albertel 3214:     my ($symb) = &get_symb($request);
1.168     albertel 3215:     #need to make sure we have the correct data for later EXT calls, 
                   3216:     #thus invalidate the cache
                   3217:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3218:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3219:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3220:     &Apache::lonnet::clear_EXT_cache_status();
                   3221: 
1.398     albertel 3222:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3223:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3224: 
                   3225:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3226:     $result.=&jscriptNform($symb);
1.41      ng       3227: 
1.44      ng       3228:     #beginning of class grading form
1.442     banghart 3229:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3230:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3231: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3232: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3233: 	&build_section_inputs().
1.257     albertel 3234: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3235: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3236: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3237: 
1.560     raeburn  3238:     my ($common_header,$specific_header);
1.257     albertel 3239:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3240: 	$common_header = &mt('Assign Common Grade to Class');
                   3241:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3242:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3243:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3244: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3245:     } else {
1.560     raeburn  3246:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3247:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3248: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3249:     }
1.560     raeburn  3250:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3251:     #radio buttons/text box for assigning points for a section or class.
                   3252:     #handles different parts of a problem
1.375     albertel 3253:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3254:     my %weight = ();
                   3255:     my $ctsparts = 0;
1.45      ng       3256:     my %seen = ();
1.375     albertel 3257:     my @part_response_id = &flatten_responseType($responseType);
                   3258:     foreach my $part_response_id (@part_response_id) {
                   3259:     	my ($partid,$respid) = @{ $part_response_id };
                   3260: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3261: 	next if $seen{$partid};
                   3262: 	$seen{$partid}++;
1.375     albertel 3263: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3264: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3265: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3266: 
1.324     albertel 3267: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3268: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3269: 	my $ctr = 0;
1.42      ng       3270: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3271: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3272: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3273: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3274: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3275: 	    $ctr++;
                   3276: 	}
1.485     albertel 3277: 	$radio.='</tr></table>';
                   3278: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3279: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3280: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3281: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3282: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3283: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3284: 		$weight{$partid}.')"> '.
1.401     albertel 3285: 	    '<option selected="selected"> </option>'.
1.485     albertel 3286: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3287: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3288: 	    '</select></td>'.
                   3289:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3290: 	$line.='<input type="hidden" name="partid_'.
                   3291: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3292: 	$line.='<input type="hidden" name="weight_'.
                   3293: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3294: 
                   3295: 	$result.=
                   3296: 	    &Apache::loncommon::start_data_table_row()."\n".
1.539     riegler  3297: 	    '<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 3298: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3299: 	$ctsparts++;
1.41      ng       3300:     }
1.474     albertel 3301:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3302: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3303:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3304: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3305: 
1.44      ng       3306:     #table listing all the students in a section/class
                   3307:     #header of table
1.560     raeburn  3308:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3309:               &Apache::loncommon::start_data_table().
                   3310: 	      &Apache::loncommon::start_data_table_header_row().
                   3311: 	      '<th>'.&mt('No.').'</th>'.
                   3312: 	      '<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3313:     my (@parts) = sort(&getpartlist($symb));
                   3314:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3315:     my @partids = ();
1.41      ng       3316:     foreach my $part (@parts) {
                   3317: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3318:         my $narrowtext = &mt('Tries');
                   3319: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3320: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3321: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3322:         push(@partids,$partid);
1.324     albertel 3323: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3324: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3325: 	    $result.='<th>'.
                   3326: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3327: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3328: 	    next;
1.485     albertel 3329: 	    
1.207     albertel 3330: 	} else {
1.485     albertel 3331: 	    if ($display =~ /Problem Status/) {
                   3332: 		my $grade_status_mt = &mt('Grade Status');
                   3333: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3334: 	    }
                   3335: 	    my $part_mt = &mt('Part:');
                   3336: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3337: 	}
1.485     albertel 3338: 
1.474     albertel 3339: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3340:     }
1.474     albertel 3341:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3342: 
1.270     albertel 3343:     my %last_resets = 
                   3344: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3345: 
1.41      ng       3346:     #get info for each student
1.44      ng       3347:     #list all the students - with points and grade status
1.257     albertel 3348:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3349:     my $ctr = 0;
1.294     albertel 3350:     foreach (sort 
                   3351: 	     {
                   3352: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3353: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3354: 		 }
                   3355: 		 return $a cmp $b;
                   3356: 	     } (keys(%$fullname))) {
1.126     ng       3357: 	$ctr++;
1.324     albertel 3358: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3359: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3360:     }
1.474     albertel 3361:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3362:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3363:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3364: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3365:     if (scalar(%$fullname) eq 0) {
                   3366: 	my $colspan=3+scalar(@parts);
1.433     banghart 3367: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3368:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3369: 	$result='<span class="LC_warning">'.
1.485     albertel 3370: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3371: 	        $section_display, $stu_status).
1.433     banghart 3372: 	    '</span>';
1.96      albertel 3373:     }
1.324     albertel 3374:     $result.=&show_grading_menu_form($symb);
1.41      ng       3375:     return $result;
                   3376: }
                   3377: 
1.44      ng       3378: #--- call by previous routine to display each student
1.41      ng       3379: sub viewstudentgrade {
1.324     albertel 3380:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3381:     my ($uname,$udom) = split(/:/,$student);
                   3382:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3383:     my %aggregates = (); 
1.474     albertel 3384:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3385: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3386: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3387: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3388: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3389: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3390:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3391:     foreach my $apart (@$parts) {
                   3392: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3393: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3394:         $result.='<td align="center">';
1.269     raeburn  3395:         my ($aggtries,$totaltries);
                   3396:         unless (exists($aggregates{$part})) {
1.270     albertel 3397: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3398: 
                   3399: 	    $aggtries = $totaltries;
1.269     raeburn  3400:             if ($$last_resets{$part}) {  
1.270     albertel 3401:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3402: 					   $part);
                   3403:             }
1.269     raeburn  3404:             $result.='<input type="hidden" name="'.
                   3405:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3406:             $result.='<input type="hidden" name="'.
                   3407:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3408:             $aggregates{$part} = 1;
                   3409:         }
1.41      ng       3410: 	if ($type eq 'awarded') {
1.320     albertel 3411: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3412: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3413: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3414: 	    $result.='<input type="text" name="'.
1.89      albertel 3415: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3416: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3417: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3418: 	} elsif ($type eq 'solved') {
                   3419: 	    my ($status,$foo)=split(/_/,$score,2);
                   3420: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3421: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3422: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3423: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3424: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3425: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3426: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3427: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3428: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3429: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3430: 	} else {
                   3431: 	    $result.='<input type="hidden" name="'.
                   3432: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3433: 		    "\n";
1.233     albertel 3434: 	    $result.='<input type="text" name="'.
1.122     ng       3435: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3436: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3437: 	}
                   3438:     }
1.474     albertel 3439:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3440:     return $result;
1.38      ng       3441: }
                   3442: 
1.44      ng       3443: #--- change scores for all the students in a section/class
                   3444: #    record does not get update if unchanged
1.38      ng       3445: sub editgrades {
1.41      ng       3446:     my ($request) = @_;
                   3447: 
1.324     albertel 3448:     my $symb=&get_symb($request);
1.433     banghart 3449:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3450:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3451:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3452:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3453: 
1.477     albertel 3454:     my $result= &Apache::loncommon::start_data_table().
                   3455: 	&Apache::loncommon::start_data_table_header_row().
                   3456: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3457: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3458:     my %scoreptr = (
                   3459: 		    'correct'  =>'correct_by_override',
                   3460: 		    'incorrect'=>'incorrect_by_override',
                   3461: 		    'excused'  =>'excused',
                   3462: 		    'ungraded' =>'ungraded_attempted',
                   3463: 		    'nothing'  => '',
                   3464: 		    );
1.257     albertel 3465:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3466: 
1.44      ng       3467:     my (@partid);
                   3468:     my %weight = ();
1.54      albertel 3469:     my %columns = ();
1.44      ng       3470:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3471: 
1.324     albertel 3472:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3473:     my $header;
1.257     albertel 3474:     while ($ctr < $env{'form.totalparts'}) {
                   3475: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3476: 	push(@partid,$partid);
1.257     albertel 3477: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3478: 	$ctr++;
1.54      albertel 3479:     }
1.324     albertel 3480:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3481:     foreach my $partid (@partid) {
1.478     albertel 3482: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3483: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3484: 	$columns{$partid}=2;
                   3485: 	foreach my $stores (@parts) {
                   3486: 	    my ($part,$type) = &split_part_type($stores);
                   3487: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3488: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3489: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3490: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3491:             my $narrowtext = &mt('Tries');
                   3492: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3493: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3494: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3495: 	    $columns{$partid}+=2;
                   3496: 	}
                   3497:     }
                   3498:     foreach my $partid (@partid) {
1.324     albertel 3499: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3500: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3501: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3502: 	    '</th>';
1.54      albertel 3503: 
1.44      ng       3504:     }
1.477     albertel 3505:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3506: 	&Apache::loncommon::start_data_table_header_row().
                   3507: 	$header.
                   3508: 	&Apache::loncommon::end_data_table_header_row();
                   3509:     my @noupdate;
1.126     ng       3510:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3511:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3512: 	my $line;
1.257     albertel 3513: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3514: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3515: 	my %newrecord;
                   3516: 	my $updateflag = 0;
1.281     albertel 3517: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3518: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3519: 	if (!&canmodify($usec)) {
1.126     ng       3520: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3521: 	    push(@noupdate,
1.478     albertel 3522: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3523: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3524: 	    next;
                   3525: 	}
1.269     raeburn  3526:         my %aggregate = ();
                   3527:         my $aggregateflag = 0;
1.281     albertel 3528: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3529: 	foreach (@partid) {
1.257     albertel 3530: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3531: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3532: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3533: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3534: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3535: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3536: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3537: 	    my $score;
                   3538: 	    if ($partial eq '') {
1.257     albertel 3539: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3540: 	    } elsif ($partial > 0) {
                   3541: 		$score = 'correct_by_override';
                   3542: 	    } elsif ($partial == 0) {
                   3543: 		$score = 'incorrect_by_override';
                   3544: 	    }
1.257     albertel 3545: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3546: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3547: 
1.292     albertel 3548: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3549: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3550: 	    if ($dropMenu eq 'reset status' &&
                   3551: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3552: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3553: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3554: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3555: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3556: 		$updateflag = 1;
1.269     raeburn  3557:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3558:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3559:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3560:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3561:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3562:                     $aggregateflag = 1;
                   3563:                 }
1.139     albertel 3564: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3565: 		$updateflag = 1;
                   3566: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3567: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3568: 		$rec_update++;
1.125     ng       3569: 	    }
                   3570: 
1.93      albertel 3571: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3572: 		'<td align="center">'.$awarded.
                   3573: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3574: 
1.54      albertel 3575: 
                   3576: 	    my $partid=$_;
                   3577: 	    foreach my $stores (@parts) {
                   3578: 		my ($part,$type) = &split_part_type($stores);
                   3579: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3580: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3581: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3582: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3583: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3584: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3585: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3586: 		    $updateflag=1;
                   3587: 		}
1.93      albertel 3588: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3589: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3590: 	    }
1.44      ng       3591: 	}
1.477     albertel 3592: 	$line.="\n";
1.301     albertel 3593: 
                   3594: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3595: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3596: 
1.44      ng       3597: 	if ($updateflag) {
                   3598: 	    $count++;
1.257     albertel 3599: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3600: 				    $udom,$uname);
1.301     albertel 3601: 
                   3602: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3603: 					      $cnum,$udom,$uname)) {
                   3604: 		# need to figure out if should be in queue.
                   3605: 		my %record =  
                   3606: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3607: 					     $udom,$uname);
                   3608: 		my $all_graded = 1;
                   3609: 		my $none_graded = 1;
                   3610: 		foreach my $part (@parts) {
                   3611: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3612: 			$all_graded = 0;
                   3613: 		    } else {
                   3614: 			$none_graded = 0;
                   3615: 		    }
                   3616: 		}
                   3617: 
                   3618: 		if ($all_graded || $none_graded) {
                   3619: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3620: 							   $symb,$cdom,$cnum,
                   3621: 							   $udom,$uname);
                   3622: 		}
                   3623: 	    }
                   3624: 
1.477     albertel 3625: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3626: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3627: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3628: 	    $updateCtr++;
1.93      albertel 3629: 	} else {
1.477     albertel 3630: 	    push(@noupdate,
                   3631: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3632: 	    $noupdateCtr++;
1.44      ng       3633: 	}
1.269     raeburn  3634:         if ($aggregateflag) {
                   3635:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3636: 				  $cdom,$cnum);
1.269     raeburn  3637:         }
1.93      albertel 3638:     }
1.477     albertel 3639:     if (@noupdate) {
1.126     ng       3640: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3641: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3642: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3643: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3644: 	    &mt('No Changes Occurred For the Students Below').
                   3645: 	    '</td>'.
1.477     albertel 3646: 	    &Apache::loncommon::end_data_table_row();
                   3647: 	foreach my $line (@noupdate) {
                   3648: 	    $result.=
                   3649: 		&Apache::loncommon::start_data_table_row().
                   3650: 		$line.
                   3651: 		&Apache::loncommon::end_data_table_row();
                   3652: 	}
1.44      ng       3653:     }
1.477     albertel 3654:     $result .= &Apache::loncommon::end_data_table().
                   3655: 	&show_grading_menu_form($symb);
1.478     albertel 3656:     my $msg = '<p><b>'.
                   3657: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3658: 	    $rec_update,$count).'</b><br />'.
                   3659: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3660: 	'</b></p>';
1.44      ng       3661:     return $title.$msg.$result;
1.5       albertel 3662: }
1.54      albertel 3663: 
                   3664: sub split_part_type {
                   3665:     my ($partstr) = @_;
                   3666:     my ($temp,@allparts)=split(/_/,$partstr);
                   3667:     my $type=pop(@allparts);
1.439     albertel 3668:     my $part=join('_',@allparts);
1.54      albertel 3669:     return ($part,$type);
                   3670: }
                   3671: 
1.44      ng       3672: #------------- end of section for handling grading by section/class ---------
                   3673: #
                   3674: #----------------------------------------------------------------------------
                   3675: 
1.5       albertel 3676: 
1.44      ng       3677: #----------------------------------------------------------------------------
                   3678: #
                   3679: #-------------------------- Next few routines handles grading by csv upload
                   3680: #
                   3681: #--- Javascript to handle csv upload
1.27      albertel 3682: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3683:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3684:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3685:   return(<<ENDPICK);
                   3686:   function verify(vf) {
                   3687:     var foundsomething=0;
                   3688:     var founduname=0;
1.243     albertel 3689:     var foundID=0;
1.27      albertel 3690:     for (i=0;i<=vf.nfields.value;i++) {
                   3691:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3692:       if (i==0 && tw!=0) { foundID=1; }
                   3693:       if (i==1 && tw!=0) { founduname=1; }
                   3694:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3695:     }
1.246     albertel 3696:     if (founduname==0 && foundID==0) {
                   3697: 	alert('$error1');
                   3698: 	return;
1.27      albertel 3699:     }
                   3700:     if (foundsomething==0) {
1.246     albertel 3701: 	alert('$error2');
                   3702: 	return;
1.27      albertel 3703:     }
                   3704:     vf.submit();
                   3705:   }
                   3706:   function flip(vf,tf) {
                   3707:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3708:     var i;
                   3709:     for (i=0;i<=vf.nfields.value;i++) {
                   3710:       //can not pick the same destination field for both name and domain
                   3711:       if (((i ==0)||(i ==1)) && 
                   3712:           ((tf==0)||(tf==1)) && 
                   3713:           (i!=tf) &&
                   3714:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3715:         eval('vf.f'+i+'.selectedIndex=0;')
                   3716:       }
                   3717:     }
                   3718:   }
                   3719: ENDPICK
                   3720: }
                   3721: 
                   3722: sub csvupload_javascript_forward_associate {
1.573     bisitz   3723:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3724:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3725:   return(<<ENDPICK);
                   3726:   function verify(vf) {
                   3727:     var foundsomething=0;
                   3728:     var founduname=0;
1.243     albertel 3729:     var foundID=0;
1.27      albertel 3730:     for (i=0;i<=vf.nfields.value;i++) {
                   3731:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3732:       if (tw==1) { foundID=1; }
                   3733:       if (tw==2) { founduname=1; }
                   3734:       if (tw>3) { foundsomething=1; }
1.27      albertel 3735:     }
1.246     albertel 3736:     if (founduname==0 && foundID==0) {
                   3737: 	alert('$error1');
                   3738: 	return;
1.27      albertel 3739:     }
                   3740:     if (foundsomething==0) {
1.246     albertel 3741: 	alert('$error2');
                   3742: 	return;
1.27      albertel 3743:     }
                   3744:     vf.submit();
                   3745:   }
                   3746:   function flip(vf,tf) {
                   3747:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3748:     var i;
                   3749:     //can not pick the same destination field twice
                   3750:     for (i=0;i<=vf.nfields.value;i++) {
                   3751:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3752:         eval('vf.f'+i+'.selectedIndex=0;')
                   3753:       }
                   3754:     }
                   3755:   }
                   3756: ENDPICK
                   3757: }
                   3758: 
1.26      albertel 3759: sub csvuploadmap_header {
1.324     albertel 3760:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3761:     my $javascript;
1.257     albertel 3762:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3763: 	$javascript=&csvupload_javascript_reverse_associate();
                   3764:     } else {
                   3765: 	$javascript=&csvupload_javascript_forward_associate();
                   3766:     }
1.45      ng       3767: 
1.324     albertel 3768:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3769:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3770:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3771:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3772:     $request->print(<<ENDPICK);
1.26      albertel 3773: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3774: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3775: $result
1.326     albertel 3776: <hr />
1.26      albertel 3777: <h3>Identify fields</h3>
                   3778: Total number of records found in file: $distotal <hr />
                   3779: Enter as many fields as you can. The system will inform you and bring you back
                   3780: to this page if the data selected is insufficient to run your class.<hr />
                   3781: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3782: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3783: <input type="hidden" name="associate"  value="" />
                   3784: <input type="hidden" name="phase"      value="three" />
                   3785: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3786: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3787: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3788: <input type="hidden" name="upfile_associate" 
1.257     albertel 3789:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3790: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3791: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3792: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3793: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3794: <hr />
                   3795: <script type="text/javascript" language="Javascript">
                   3796: $javascript
                   3797: </script>
                   3798: ENDPICK
1.118     ng       3799:     return '';
1.26      albertel 3800: 
                   3801: }
                   3802: 
                   3803: sub csvupload_fields {
1.324     albertel 3804:     my ($symb) = @_;
                   3805:     my (@parts) = &getpartlist($symb);
1.556     weissno  3806:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3807: 		['username','Student Username'],
                   3808: 		['domain','Student Domain']);
1.324     albertel 3809:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3810:     foreach my $part (sort(@parts)) {
                   3811: 	my @datum;
                   3812: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3813: 	my $name=$part;
                   3814: 	if  (!$display) { $display = $name; }
                   3815: 	@datum=($name,$display);
1.244     albertel 3816: 	if ($name=~/^stores_(.*)_awarded/) {
                   3817: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3818: 	}
1.41      ng       3819: 	push(@fields,\@datum);
                   3820:     }
                   3821:     return (@fields);
1.26      albertel 3822: }
                   3823: 
                   3824: sub csvuploadmap_footer {
1.41      ng       3825:     my ($request,$i,$keyfields) =@_;
                   3826:     $request->print(<<ENDPICK);
1.26      albertel 3827: </table>
                   3828: <input type="hidden" name="nfields" value="$i" />
                   3829: <input type="hidden" name="keyfields" value="$keyfields" />
                   3830: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3831: </form>
                   3832: ENDPICK
                   3833: }
                   3834: 
1.283     albertel 3835: sub checkforfile_js {
1.539     riegler  3836:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       3837:     my $result =<<CSVFORMJS;
                   3838: <script type="text/javascript" language="javascript">
                   3839:     function checkUpload(formname) {
                   3840: 	if (formname.upfile.value == "") {
1.539     riegler  3841: 	    alert("$alertmsg");
1.86      ng       3842: 	    return false;
                   3843: 	}
                   3844: 	formname.submit();
                   3845:     }
                   3846:     </script>
                   3847: CSVFORMJS
1.283     albertel 3848:     return $result;
                   3849: }
                   3850: 
                   3851: sub upcsvScores_form {
                   3852:     my ($request) = shift;
1.324     albertel 3853:     my ($symb)=&get_symb($request);
1.283     albertel 3854:     if (!$symb) {return '';}
                   3855:     my $result=&checkforfile_js();
1.257     albertel 3856:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3857:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3858:     $result.=$table;
1.326     albertel 3859:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3860:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3861:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3862: 	'</b></td></tr>'."\n";
1.86      ng       3863:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3864:     my $upload=&mt("Upload Scores");
1.86      ng       3865:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3866:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3867:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3868:     $result.=<<ENDUPFORM;
1.106     albertel 3869: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3870: <input type="hidden" name="symb" value="$symb" />
                   3871: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3872: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3873: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3874: $upfile_select
1.370     www      3875: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3876: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3877: </form>
                   3878: ENDUPFORM
1.370     www      3879:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3880:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3881:     .'</td></tr></table>'."\n";
1.86      ng       3882:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3883:     $result.=&show_grading_menu_form($symb);
1.86      ng       3884:     return $result;
                   3885: }
                   3886: 
                   3887: 
1.26      albertel 3888: sub csvuploadmap {
1.41      ng       3889:     my ($request)= @_;
1.324     albertel 3890:     my ($symb)=&get_symb($request);
1.41      ng       3891:     if (!$symb) {return '';}
1.72      ng       3892: 
1.41      ng       3893:     my $datatoken;
1.257     albertel 3894:     if (!$env{'form.datatoken'}) {
1.41      ng       3895: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3896:     } else {
1.257     albertel 3897: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3898: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3899:     }
1.41      ng       3900:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3901:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3902:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3903:     my ($i,$keyfields);
                   3904:     if (@records) {
1.324     albertel 3905: 	my @fields=&csvupload_fields($symb);
1.45      ng       3906: 
1.257     albertel 3907: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3908: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3909: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3910: 							  \@fields);
                   3911: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3912: 	    chop($keyfields);
                   3913: 	} else {
                   3914: 	    unshift(@fields,['none','']);
                   3915: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3916: 							    \@fields);
1.311     banghart 3917:             foreach my $rec (@records) {
                   3918:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3919:                 if (%temp) {
                   3920:                     $keyfields=join(',',sort(keys(%temp)));
                   3921:                     last;
                   3922:                 }
                   3923:             }
1.41      ng       3924: 	}
                   3925:     }
                   3926:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3927:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3928: 
1.41      ng       3929:     return '';
1.27      albertel 3930: }
                   3931: 
1.246     albertel 3932: sub csvuploadoptions {
1.41      ng       3933:     my ($request)= @_;
1.324     albertel 3934:     my ($symb)=&get_symb($request);
1.257     albertel 3935:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3936:     my $ignore=&mt('Ignore First Line');
                   3937:     $request->print(<<ENDPICK);
                   3938: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3939: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3940: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3941: <!--
1.246     albertel 3942: <p>
                   3943: <label>
                   3944:    <input type="checkbox" name="show_full_results" />
                   3945:    Show a table of all changes
                   3946: </label>
                   3947: </p>
1.302     albertel 3948: -->
1.246     albertel 3949: <p>
                   3950: <label>
                   3951:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3952:    Overwrite any existing score
                   3953: </label>
                   3954: </p>
                   3955: ENDPICK
                   3956:     my %fields=&get_fields();
                   3957:     if (!defined($fields{'domain'})) {
1.257     albertel 3958: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3959: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3960:     }
1.257     albertel 3961:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3962: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3963: 	my $cleankey=$1;
                   3964: 	if ($cleankey eq 'command') { next; }
                   3965: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3966: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3967:     }
                   3968:     # FIXME do a check for any duplicated user ids...
                   3969:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3970:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3971: <hr /></form>'."\n");
1.324     albertel 3972:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3973:     return '';
                   3974: }
                   3975: 
                   3976: sub get_fields {
                   3977:     my %fields;
1.257     albertel 3978:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3979:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3980: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3981: 	    if ($env{'form.f'.$i} ne 'none') {
                   3982: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3983: 	    }
                   3984: 	} else {
1.257     albertel 3985: 	    if ($env{'form.f'.$i} ne 'none') {
                   3986: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3987: 	    }
                   3988: 	}
1.27      albertel 3989:     }
1.246     albertel 3990:     return %fields;
                   3991: }
                   3992: 
                   3993: sub csvuploadassign {
                   3994:     my ($request)= @_;
1.324     albertel 3995:     my ($symb)=&get_symb($request);
1.246     albertel 3996:     if (!$symb) {return '';}
1.345     bowersj2 3997:     my $error_msg = '';
1.246     albertel 3998:     &Apache::loncommon::load_tmp_file($request);
                   3999:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4000:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4001:     my %fields=&get_fields();
1.41      ng       4002:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4003:     my $courseid=$env{'request.course.id'};
1.97      albertel 4004:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4005:     my @notallowed;
1.41      ng       4006:     my @skipped;
                   4007:     my $countdone=0;
                   4008:     foreach my $grade (@gradedata) {
                   4009: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4010: 	my $domain;
                   4011: 	if ($entries{$fields{'domain'}}) {
                   4012: 	    $domain=$entries{$fields{'domain'}};
                   4013: 	} else {
1.257     albertel 4014: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4015: 	}
1.243     albertel 4016: 	$domain=~s/\s//g;
1.41      ng       4017: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4018: 	$username=~s/\s//g;
1.243     albertel 4019: 	if (!$username) {
                   4020: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4021: 	    $id=~s/\s//g;
1.243     albertel 4022: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4023: 	    $username=$ids{$id};
                   4024: 	}
1.41      ng       4025: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4026: 	    my $id=$entries{$fields{'ID'}};
                   4027: 	    $id=~s/\s//g;
                   4028: 	    if ($id) {
                   4029: 		push(@skipped,"$id:$domain");
                   4030: 	    } else {
                   4031: 		push(@skipped,"$username:$domain");
                   4032: 	    }
1.41      ng       4033: 	    next;
                   4034: 	}
1.108     albertel 4035: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4036: 	if (!&canmodify($usec)) {
                   4037: 	    push(@notallowed,"$username:$domain");
                   4038: 	    next;
                   4039: 	}
1.244     albertel 4040: 	my %points;
1.41      ng       4041: 	my %grades;
                   4042: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4043: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4044: 		$dest eq 'domain') { next; }
                   4045: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4046: 	    if ($dest=~/stores_(.*)_points/) {
                   4047: 		my $part=$1;
                   4048: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4049: 					      $symb,$domain,$username);
1.345     bowersj2 4050:                 if ($wgt) {
                   4051:                     $entries{$fields{$dest}}=~s/\s//g;
                   4052:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4053:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4054:                                           : 'correct_by_override';
1.345     bowersj2 4055:                     $grades{"resource.$part.awarded"}=$pcr;
                   4056:                     $grades{"resource.$part.solved"}=$award;
                   4057:                     $points{$part}=1;
                   4058:                 } else {
                   4059:                     $error_msg = "<br />" .
                   4060:                         &mt("Some point values were assigned"
                   4061:                             ." for problems with a weight "
                   4062:                             ."of zero. These values were "
                   4063:                             ."ignored.");
                   4064:                 }
1.244     albertel 4065: 	    } else {
                   4066: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4067: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4068: 		my $store_key=$dest;
                   4069: 		$store_key=~s/^stores/resource/;
                   4070: 		$store_key=~s/_/\./g;
                   4071: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4072: 	    }
1.41      ng       4073: 	}
1.508     www      4074: 	if (! %grades) { 
                   4075:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4076:         } else {
                   4077: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4078: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4079: 					   $env{'request.course.id'},
                   4080: 					   $domain,$username);
1.508     www      4081: 	   if ($result eq 'ok') {
                   4082: 	      $request->print('.');
                   4083: 	   } else {
                   4084: 	      $request->print("<p><span class=\"LC_error\">".
                   4085:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4086:                                   "$username:$domain",$result)."</span></p>");
                   4087: 	   }
                   4088: 	   $request->rflush();
                   4089: 	   $countdone++;
                   4090:         }
1.41      ng       4091:     }
1.570     www      4092:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4093:     if (@skipped) {
1.571     www      4094: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4095:         $request->print(join(', ',@skipped));
1.106     albertel 4096:     }
                   4097:     if (@notallowed) {
1.571     www      4098: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4099: 	$request->print(join(', ',@notallowed));
1.41      ng       4100:     }
1.106     albertel 4101:     $request->print("<br />\n");
1.324     albertel 4102:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4103:     return $error_msg;
1.26      albertel 4104: }
1.44      ng       4105: #------------- end of section for handling csv file upload ---------
                   4106: #
                   4107: #-------------------------------------------------------------------
                   4108: #
1.122     ng       4109: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4110: #
                   4111: #--- Select a page/sequence and a student to grade
1.68      ng       4112: sub pickStudentPage {
                   4113:     my ($request) = shift;
                   4114: 
1.539     riegler  4115:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4116:     $request->print(<<LISTJAVASCRIPT);
                   4117: <script type="text/javascript" language="javascript">
                   4118: 
                   4119: function checkPickOne(formname) {
1.76      ng       4120:     if (radioSelection(formname.student) == null) {
1.539     riegler  4121: 	alert("$alertmsg");
1.68      ng       4122: 	return;
                   4123:     }
1.125     ng       4124:     ptr = pullDownSelection(formname.selectpage);
                   4125:     formname.page.value = formname["page"+ptr].value;
                   4126:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4127:     formname.submit();
                   4128: }
                   4129: 
                   4130: </script>
                   4131: LISTJAVASCRIPT
1.118     ng       4132:     &commonJSfunctions($request);
1.324     albertel 4133:     my ($symb) = &get_symb($request);
1.257     albertel 4134:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4135:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4136:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4137: 
1.398     albertel 4138:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4139: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4140: 
1.80      ng       4141:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4142:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4143:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4144: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4145: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4146:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4147:     my $ctr=0;
1.68      ng       4148:     foreach (@$titles) {
                   4149: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4150: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4151: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4152: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4153: 	$ctr++;
1.68      ng       4154:     }
1.485     albertel 4155:     $select.= '</select>';
1.539     riegler  4156:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4157: 
1.70      ng       4158:     $ctr=0;
                   4159:     foreach (@$titles) {
                   4160: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4161: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4162: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4163: 	$ctr++;
                   4164:     }
1.72      ng       4165:     $result.='<input type="hidden" name="page" />'."\n".
                   4166: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4167: 
1.485     albertel 4168:     my $options =
                   4169: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4170: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4171:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4172: 
                   4173:     $options =
                   4174: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4175: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4176: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4177:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4178:     
                   4179:     $result.=&build_section_inputs();
1.442     banghart 4180:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4181:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4182: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4183: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4184: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4185: 
1.539     riegler  4186:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4187: 
1.80      ng       4188:     $result.='&nbsp;<input type="button" '.
1.539     riegler  4189: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4190: 
1.68      ng       4191:     $request->print($result);
                   4192: 
1.485     albertel 4193:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4194: 	&Apache::loncommon::start_data_table().
                   4195: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4196: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4197: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4198: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4199: 	'<th>'.&nameUserString('header').'</th>'.
                   4200: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4201:  
1.76      ng       4202:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4203:     my $ptr = 1;
1.294     albertel 4204:     foreach my $student (sort 
                   4205: 			 {
                   4206: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4207: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4208: 			     }
                   4209: 			     return $a cmp $b;
                   4210: 			 } (keys(%$fullname))) {
1.68      ng       4211: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4212: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4213:                                   : '</td>');
1.126     ng       4214: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4215: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4216: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4217: 	$studentTable.=
                   4218: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4219:                          : '');
1.68      ng       4220: 	$ptr++;
                   4221:     }
1.484     albertel 4222:     if ($ptr%2 == 0) {
                   4223: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4224: 	    &Apache::loncommon::end_data_table_row();
                   4225:     }
                   4226:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4227:     $studentTable.='<input type="button" '.
1.539     riegler  4228: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4229: 
1.324     albertel 4230:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4231:     $request->print($studentTable);
                   4232: 
                   4233:     return '';
                   4234: }
                   4235: 
                   4236: sub getSymbMap {
1.132     bowersj2 4237:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4238: 
                   4239:     my %symbx = ();
                   4240:     my @titles = ();
1.117     bowersj2 4241:     my $minder = 0;
                   4242: 
                   4243:     # Gather every sequence that has problems.
1.240     albertel 4244:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4245: 					       1,0,1);
1.117     bowersj2 4246:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4247: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4248: 	    my $title = $minder.'.'.
                   4249: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4250: 	    push(@titles, $title); # minder in case two titles are identical
                   4251: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4252: 	    $minder++;
1.241     albertel 4253: 	}
1.68      ng       4254:     }
                   4255:     return \@titles,\%symbx;
                   4256: }
                   4257: 
1.72      ng       4258: #
                   4259: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4260: sub displayPage {
                   4261:     my ($request) = shift;
                   4262: 
1.324     albertel 4263:     my ($symb) = &get_symb($request);
1.257     albertel 4264:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4265:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4266:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4267:     my $pageTitle = $env{'form.page'};
1.103     albertel 4268:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4269:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4270:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4271: 
                   4272:     #need to make sure we have the correct data for later EXT calls, 
                   4273:     #thus invalidate the cache
                   4274:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4275:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4276:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4277:     &Apache::lonnet::clear_EXT_cache_status();
                   4278: 
1.103     albertel 4279:     if (!&canview($usec)) {
1.485     albertel 4280: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4281: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4282: 	return;
                   4283:     }
1.398     albertel 4284:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4285:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4286: 	'</h3>'."\n";
1.500     albertel 4287:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4288:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4289: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4290:     } else {
                   4291: 	delete($env{'form.CODE'});
                   4292:     }
1.71      ng       4293:     &sub_page_js($request);
                   4294:     $request->print($result);
                   4295: 
1.132     bowersj2 4296:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4297:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4298:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4299:     if (!$map) {
1.485     albertel 4300: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4301: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4302: 	return; 
                   4303:     }
1.68      ng       4304:     my $iterator = $navmap->getIterator($map->map_start(),
                   4305: 					$map->map_finish());
                   4306: 
1.71      ng       4307:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4308: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4309: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4310: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4311: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4312: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4313: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4314: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4315: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4316: 
1.382     albertel 4317:     if (defined($env{'form.CODE'})) {
                   4318: 	$studentTable.=
                   4319: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4320:     }
1.381     albertel 4321:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4322: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4323: 
1.485     albertel 4324:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4325: 	&Apache::loncommon::start_data_table().
                   4326: 	&Apache::loncommon::start_data_table_header_row().
                   4327: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4328: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4329: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4330: 
1.329     albertel 4331:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4332:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4333:     $iterator->next(); # skip the first BEGIN_MAP
                   4334:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4335:     while ($depth > 0) {
1.68      ng       4336:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4337:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4338: 
1.385     albertel 4339:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4340: 	    my $parts = $curRes->parts();
1.68      ng       4341:             my $title = $curRes->compTitle();
1.71      ng       4342: 	    my $symbx = $curRes->symb();
1.484     albertel 4343: 	    $studentTable.=
                   4344: 		&Apache::loncommon::start_data_table_row().
                   4345: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4346: 		(scalar(@{$parts}) == 1 ? '' 
                   4347: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4348: 							scalar(@{$parts}))
                   4349: 		 ).
                   4350: 		 '</td>';
1.71      ng       4351: 	    $studentTable.='<td valign="top">';
1.382     albertel 4352: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4353: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4354: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4355: 					     undef,'both',\%form);
1.71      ng       4356: 	    } else {
1.382     albertel 4357: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4358: 		$companswer =~ s|<form(.*?)>||g;
                   4359: 		$companswer =~ s|</form>||g;
1.71      ng       4360: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4361: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4362: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4363: #		}
1.116     ng       4364: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4365: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4366: 	    }
                   4367: 
1.257     albertel 4368: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4369: 
1.257     albertel 4370: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4371: 		if ($record{'version'} eq '') {
1.485     albertel 4372: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4373: 		} else {
1.116     ng       4374: 		    my %responseType = ();
                   4375: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4376: 			my @responseIds =$curRes->responseIds($partid);
                   4377: 			my @responseType =$curRes->responseType($partid);
                   4378: 			my %responseIds;
                   4379: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4380: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4381: 			}
                   4382: 			$responseType{$partid} = \%responseIds;
1.116     ng       4383: 		    }
1.148     albertel 4384: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4385: 
1.71      ng       4386: 		}
1.257     albertel 4387: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4388: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4389: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4390: 									$env{'request.course.id'},
1.71      ng       4391: 									'','.submission');
                   4392:  
                   4393: 	    }
1.103     albertel 4394: 	    if (&canmodify($usec)) {
                   4395: 		foreach my $partid (@{$parts}) {
                   4396: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4397: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4398: 		    $question++;
                   4399: 		}
1.196     albertel 4400: 		$prob++;
1.71      ng       4401: 	    }
                   4402: 	    $studentTable.='</td></tr>';
1.68      ng       4403: 
1.103     albertel 4404: 	}
1.68      ng       4405:         $curRes = $iterator->next();
                   4406:     }
                   4407: 
1.485     albertel 4408:     $studentTable.='</table>'."\n".
                   4409: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4410: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4411: 	'</form>'."\n";
1.324     albertel 4412:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4413:     $request->print($studentTable);
                   4414: 
                   4415:     return '';
1.119     ng       4416: }
                   4417: 
                   4418: sub displaySubByDates {
1.148     albertel 4419:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4420:     my $isCODE=0;
1.335     albertel 4421:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4422:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4423:     my $studentTable=&Apache::loncommon::start_data_table().
                   4424: 	&Apache::loncommon::start_data_table_header_row().
                   4425: 	'<th>'.&mt('Date/Time').'</th>'.
                   4426: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4427: 	'<th>'.&mt('Submission').'</th>'.
                   4428: 	'<th>'.&mt('Status').'</th>'.
                   4429: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4430:     my ($version);
                   4431:     my %mark;
1.148     albertel 4432:     my %orders;
1.119     ng       4433:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4434:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4435: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4436:     }
1.335     albertel 4437: 
                   4438:     my $interaction;
1.525     raeburn  4439:     my $no_increment = 1;
1.119     ng       4440:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4441: 	my $timestamp = 
                   4442: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4443: 	if (exists($$record{$version.':resource.0.version'})) {
                   4444: 	    $interaction = $$record{$version.':resource.0.version'};
                   4445: 	}
                   4446: 
                   4447: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4448: 		             : "$version:resource");
1.467     albertel 4449: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4450: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4451: 	if ($isCODE) {
                   4452: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4453: 	}
1.119     ng       4454: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4455: 	my @displaySub = ();
                   4456: 	foreach my $partid (@{$parts}) {
1.335     albertel 4457: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4458: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4459: 	    
                   4460: 
1.122     ng       4461: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4462: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4463: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4464: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4465: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4466: 
                   4467: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4468: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4469: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4470: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4471: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4472: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4473: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4474: 		    } else {
1.467     albertel 4475: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4476: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4477: 		    }
1.335     albertel 4478: 		    my $responseType=($isTask ? 'Task'
                   4479:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4480: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4481: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4482: 			$orders{$partid}->{$responseId}=
1.525     raeburn  4483: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
                   4484:                                        $no_increment);
1.148     albertel 4485: 		    }
1.147     albertel 4486: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4487: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4488: 		}
                   4489: 	    }
1.335     albertel 4490: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4491: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4492: 				    $$record{"$where.$partid.checkedin"},
                   4493: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4494: 					'<br />';
1.335     albertel 4495: 	    }
                   4496: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4497: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4498: 		    lc($$record{"$where.$partid.award"}).' '.
                   4499: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4500: 		    '<br />';
                   4501: 	    }
1.335     albertel 4502: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4503: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4504: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4505: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4506: 		$displaySub[2].=
                   4507: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4508: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4509: 	    }
                   4510: 	}
                   4511: 	# needed because old essay regrader has not parts info
                   4512: 	if (exists $$record{"$version:resource.regrader"}) {
                   4513: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4514: 	}
                   4515: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4516: 	if ($displaySub[2]) {
1.467     albertel 4517: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4518: 	}
1.467     albertel 4519: 	$studentTable.='&nbsp;</td>'.
                   4520: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4521:     }
1.467     albertel 4522:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4523:     return $studentTable;
1.71      ng       4524: }
                   4525: 
                   4526: sub updateGradeByPage {
                   4527:     my ($request) = shift;
                   4528: 
1.257     albertel 4529:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4530:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4531:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4532:     my $pageTitle = $env{'form.page'};
1.103     albertel 4533:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4534:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4535:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4536:     if (!&canmodify($usec)) {
1.526     raeburn  4537: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4538: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4539: 	return;
                   4540:     }
1.398     albertel 4541:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4542:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4543: 	'</h3>'."\n";
1.70      ng       4544: 
1.68      ng       4545:     $request->print($result);
                   4546: 
1.132     bowersj2 4547:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4548:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4549:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4550:     if (!$map) {
1.527     raeburn  4551: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4552: 	my ($symb)=&get_symb($request);
                   4553: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4554: 	return; 
                   4555:     }
1.71      ng       4556:     my $iterator = $navmap->getIterator($map->map_start(),
                   4557: 					$map->map_finish());
1.70      ng       4558: 
1.484     albertel 4559:     my $studentTable=
                   4560: 	&Apache::loncommon::start_data_table().
                   4561: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4562: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4563: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4564: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4565: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4566: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4567: 
                   4568:     $iterator->next(); # skip the first BEGIN_MAP
                   4569:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4570:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4571:     while ($depth > 0) {
1.71      ng       4572:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4573:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4574: 
1.385     albertel 4575:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4576: 	    my $parts = $curRes->parts();
1.71      ng       4577:             my $title = $curRes->compTitle();
                   4578: 	    my $symbx = $curRes->symb();
1.484     albertel 4579: 	    $studentTable.=
                   4580: 		&Apache::loncommon::start_data_table_row().
                   4581: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4582: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4583:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4584: 		.')').'</td>';
1.71      ng       4585: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4586: 
                   4587: 	    my %newrecord=();
                   4588: 	    my @displayPts=();
1.269     raeburn  4589:             my %aggregate = ();
                   4590:             my $aggregateflag = 0;
1.71      ng       4591: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4592: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4593: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4594: 
1.257     albertel 4595: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4596: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4597: 		my $partial = $newpts/$wgt;
                   4598: 		my $score;
                   4599: 		if ($partial > 0) {
                   4600: 		    $score = 'correct_by_override';
1.125     ng       4601: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4602: 		    $score = 'incorrect_by_override';
                   4603: 		}
1.257     albertel 4604: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4605: 		if ($dropMenu eq 'excused') {
1.71      ng       4606: 		    $partial = '';
                   4607: 		    $score = 'excused';
1.125     ng       4608: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4609: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4610: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4611: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4612: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4613: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4614: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4615: 		    $changeflag++;
                   4616: 		    $newpts = '';
1.269     raeburn  4617:                     
                   4618:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4619:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4620:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4621:                     if ($aggtries > 0) {
                   4622:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4623:                         $aggregateflag = 1;
                   4624:                     }
1.71      ng       4625: 		}
1.324     albertel 4626: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4627: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4628: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4629: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4630: 		    '&nbsp;<br />';
1.526     raeburn  4631: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4632: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4633: 		    '&nbsp;<br />';
1.71      ng       4634: 		$question++;
1.380     albertel 4635: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4636: 
1.71      ng       4637: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4638: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4639: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4640: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4641: 
                   4642: 		$changeflag++;
                   4643: 	    }
                   4644: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4645: 		my %record = 
                   4646: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4647: 					     $udom,$uname);
                   4648: 
                   4649: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4650: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4651: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4652: 		    $newrecord{'resource.CODE'} = '';
                   4653: 		}
1.257     albertel 4654: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4655: 					$udom,$uname);
1.382     albertel 4656: 		%record = &Apache::lonnet::restore($symbx,
                   4657: 						   $env{'request.course.id'},
                   4658: 						   $udom,$uname);
1.380     albertel 4659: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4660: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4661: 	    }
1.380     albertel 4662: 	    
1.269     raeburn  4663:             if ($aggregateflag) {
                   4664:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4665:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4666:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4667:             }
1.125     ng       4668: 
1.71      ng       4669: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4670: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4671: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4672: 
1.196     albertel 4673: 	    $prob++;
1.68      ng       4674: 	}
1.71      ng       4675:         $curRes = $iterator->next();
1.68      ng       4676:     }
1.98      albertel 4677: 
1.484     albertel 4678:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4679:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4680:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4681: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4682: 		  $changeflag));
1.76      ng       4683:     $request->print($grademsg.$studentTable);
1.68      ng       4684: 
1.70      ng       4685:     return '';
                   4686: }
                   4687: 
1.72      ng       4688: #-------- end of section for handling grading by page/sequence ---------
                   4689: #
                   4690: #-------------------------------------------------------------------
                   4691: 
1.75      albertel 4692: #--------------------Scantron Grading-----------------------------------
                   4693: #
                   4694: #------ start of section for handling grading by page/sequence ---------
                   4695: 
1.423     albertel 4696: =pod
                   4697: 
                   4698: =head1 Bubble sheet grading routines
                   4699: 
1.424     albertel 4700:   For this documentation:
                   4701: 
                   4702:    'scanline' refers to the full line of characters
                   4703:    from the file that we are parsing that represents one entire sheet
                   4704: 
                   4705:    'bubble line' refers to the data
                   4706:    representing the line of bubbles that are on the physical bubble sheet
                   4707: 
                   4708: 
                   4709: The overall process is that a scanned in bubble sheet data is uploaded
                   4710: into a course. When a user wants to grade, they select a
                   4711: sequence/folder of resources, a file of bubble sheet info, and pick
                   4712: one of the predefined configurations for what each scanline looks
                   4713: like.
                   4714: 
                   4715: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4716: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4717: because too light bubbling), 'double bubble' (each bubble line should
                   4718: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4719: invalid student/employee ID
1.424     albertel 4720: 
                   4721: If the CODE option is used that determines the randomization of the
1.556     weissno  4722: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4723: username:domain.
                   4724: 
                   4725: During the validation phase the instructor can choose to skip scanlines. 
                   4726: 
1.435     foxr     4727: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4728: 
                   4729:   scantron_original_filename (unmodified original file)
                   4730:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4731:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4732: 
                   4733: Also there is a separate hash nohist_scantrondata that contains extra
                   4734: correction information that isn't representable in the bubble sheet
                   4735: file (see &scantron_getfile() for more information)
                   4736: 
                   4737: After all scanlines are either valid, marked as valid or skipped, then
                   4738: foreach line foreach problem in the picked sequence, an ssi request is
                   4739: made that simulates a user submitting their selected letter(s) against
                   4740: the homework problem.
1.423     albertel 4741: 
                   4742: =over 4
                   4743: 
                   4744: 
                   4745: 
                   4746: =item defaultFormData
                   4747: 
                   4748:   Returns html hidden inputs used to hold context/default values.
                   4749: 
                   4750:  Arguments:
                   4751:   $symb - $symb of the current resource 
                   4752: 
                   4753: =cut
1.422     foxr     4754: 
1.81      albertel 4755: sub defaultFormData {
1.324     albertel 4756:     my ($symb)=@_;
1.447     foxr     4757:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4758:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4759:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4760: }
                   4761: 
1.447     foxr     4762: 
1.423     albertel 4763: =pod 
                   4764: 
                   4765: =item getSequenceDropDown
                   4766: 
                   4767:    Return html dropdown of possible sequences to grade
                   4768:  
                   4769:  Arguments:
                   4770:    $symb - $symb of the current resource 
                   4771: 
                   4772: =cut
1.422     foxr     4773: 
1.75      albertel 4774: sub getSequenceDropDown {
1.423     albertel 4775:     my ($symb)=@_;
1.75      albertel 4776:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4777:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4778:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4779:     my $ctr=0;
                   4780:     foreach (@$titles) {
                   4781: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4782: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4783: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4784: 	    '>'.$showtitle.'</option>'."\n";
                   4785: 	$ctr++;
                   4786:     }
                   4787:     $result.= '</select>';
                   4788:     return $result;
                   4789: }
                   4790: 
1.495     albertel 4791: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4792:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4793: 
                   4794: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4795: 
1.509     raeburn  4796: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4797:                                    # matchresponse or rankresponse, where 
                   4798:                                    # an individual response can have multiple 
                   4799:                                    # lines
1.503     raeburn  4800: 
                   4801: my %responsetype_per_response;     # responsetype for each response
                   4802: 
1.495     albertel 4803: # Save and restore the bubble lines array to the form env.
                   4804: 
                   4805: 
                   4806: sub save_bubble_lines {
                   4807:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4808: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4809: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4810: 	    $first_bubble_line{$line};
1.503     raeburn  4811:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4812:             $subdivided_bubble_lines{$line};
                   4813:         $env{"form.scantron.responsetype.$line"} =
                   4814:             $responsetype_per_response{$line};
1.495     albertel 4815:     }
                   4816: }
                   4817: 
                   4818: 
                   4819: sub restore_bubble_lines {
                   4820:     my $line = 0;
                   4821:     %bubble_lines_per_response = ();
                   4822:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4823: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4824: 	$bubble_lines_per_response{$line} = $value;
                   4825: 	$first_bubble_line{$line}  =
                   4826: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4827:         $subdivided_bubble_lines{$line} =
                   4828:             $env{"form.scantron.sub_bubblelines.$line"};
                   4829:         $responsetype_per_response{$line} =
                   4830:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4831: 	$line++;
                   4832:     }
                   4833: }
                   4834: 
                   4835: #  Given the parsed scanline, get the response for 
                   4836: #  'answer' number n:
                   4837: 
                   4838: sub get_response_bubbles {
                   4839:     my ($parsed_line, $response)  = @_;
                   4840: 
                   4841:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4842:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4843:     
                   4844:     my $selected = "";
                   4845: 
                   4846:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4847: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4848: 	$bubble_line++;
                   4849:     }
                   4850:     return $selected;
                   4851: }
1.423     albertel 4852: 
                   4853: =pod 
                   4854: 
                   4855: =item scantron_filenames
                   4856: 
                   4857:    Returns a list of the scantron files in the current course 
                   4858: 
                   4859: =cut
1.422     foxr     4860: 
1.202     albertel 4861: sub scantron_filenames {
1.257     albertel 4862:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4863:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4864:     my $getpropath = 1;
1.157     albertel 4865:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4866:                                        $getpropath);
1.202     albertel 4867:     my @possiblenames;
1.201     albertel 4868:     foreach my $filename (sort(@files)) {
1.157     albertel 4869: 	($filename)=split(/&/,$filename);
                   4870: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4871: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4872: 	push(@possiblenames,$filename);
                   4873:     }
                   4874:     return @possiblenames;
                   4875: }
                   4876: 
1.423     albertel 4877: =pod 
                   4878: 
                   4879: =item scantron_uploads
                   4880: 
                   4881:    Returns  html drop-down list of scantron files in current course.
                   4882: 
                   4883:  Arguments:
                   4884:    $file2grade - filename to set as selected in the dropdown
                   4885: 
                   4886: =cut
1.422     foxr     4887: 
1.202     albertel 4888: sub scantron_uploads {
1.209     ng       4889:     my ($file2grade) = @_;
1.202     albertel 4890:     my $result=	'<select name="scantron_selectfile">';
                   4891:     $result.="<option></option>";
                   4892:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4893: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4894:     }
                   4895:     $result.="</select>";
                   4896:     return $result;
                   4897: }
                   4898: 
1.423     albertel 4899: =pod 
                   4900: 
                   4901: =item scantron_scantab
                   4902: 
                   4903:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4904:   file.
                   4905: 
                   4906: =cut
1.422     foxr     4907: 
1.82      albertel 4908: sub scantron_scantab {
                   4909:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4910:     $result.='<option></option>'."\n";
1.518     raeburn  4911:     my @lines = &get_scantronformat_file();
                   4912:     if (@lines > 0) {
                   4913:         foreach my $line (@lines) {
                   4914:             next if (($line =~ /^\#/) || ($line eq ''));
                   4915: 	    my ($name,$descrip)=split(/:/,$line);
                   4916: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4917:         }
1.82      albertel 4918:     }
                   4919:     $result.='</select>'."\n";
1.518     raeburn  4920:     return $result;
                   4921: }
                   4922: 
                   4923: =pod
                   4924: 
                   4925: =item get_scantronformat_file
                   4926: 
                   4927:   Returns an array containing lines from the scantron format file for
                   4928:   the domain of the course.
                   4929: 
                   4930:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4931:   lines are from this file.
                   4932: 
                   4933:   Otherwise, if a default.tab has been published in RES space by the 
                   4934:   domainconfig user, lines are from this file.
                   4935: 
                   4936:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4937:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4938: 
1.518     raeburn  4939: =cut
                   4940: 
                   4941: sub get_scantronformat_file {
                   4942:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4943:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   4944:     my $gottab = 0;
                   4945:     my @lines;
                   4946:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4947:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4948:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4949:             if ($formatfile ne '-1') {
                   4950:                 @lines = split("\n",$formatfile,-1);
                   4951:                 $gottab = 1;
                   4952:             }
                   4953:         }
                   4954:     }
                   4955:     if (!$gottab) {
                   4956:         my $confname = $cdom.'-domainconfig';
                   4957:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4958:         my $formatfile =  &Apache::lonnet::getfile($default);
                   4959:         if ($formatfile ne '-1') {
                   4960:             @lines = split("\n",$formatfile,-1);
                   4961:             $gottab = 1;
                   4962:         }
                   4963:     }
                   4964:     if (!$gottab) {
1.519     raeburn  4965:         my @domains = &Apache::lonnet::current_machine_domains();
                   4966:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4967:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4968:             @lines = <$fh>;
                   4969:             close($fh);
                   4970:         } else {
                   4971:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   4972:             @lines = <$fh>;
                   4973:             close($fh);
                   4974:         }
1.518     raeburn  4975:     }
                   4976:     return @lines;
1.82      albertel 4977: }
                   4978: 
1.423     albertel 4979: =pod 
                   4980: 
                   4981: =item scantron_CODElist
                   4982: 
                   4983:   Returns html drop down of the saved CODE lists from current course,
                   4984:   generated from earlier printings.
                   4985: 
                   4986: =cut
1.422     foxr     4987: 
1.186     albertel 4988: sub scantron_CODElist {
1.257     albertel 4989:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4990:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4991:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4992:     my $namechoice='<option></option>';
1.225     albertel 4993:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4994: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4995: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4996: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4997:     }
                   4998:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4999:     return $namechoice;
                   5000: }
                   5001: 
1.423     albertel 5002: =pod 
                   5003: 
                   5004: =item scantron_CODEunique
                   5005: 
                   5006:   Returns the html for "Each CODE to be used once" radio.
                   5007: 
                   5008: =cut
1.422     foxr     5009: 
1.186     albertel 5010: sub scantron_CODEunique {
1.532     bisitz   5011:     my $result='<span class="LC_nobreak">
1.272     albertel 5012:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5013:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5014:                 </span>
1.532     bisitz   5015:                 <span class="LC_nobreak">
1.272     albertel 5016:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5017:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5018:                 </span>';
1.186     albertel 5019:     return $result;
                   5020: }
1.423     albertel 5021: 
                   5022: =pod 
                   5023: 
                   5024: =item scantron_selectphase
                   5025: 
                   5026:   Generates the initial screen to start the bubble sheet process.
                   5027:   Allows for - starting a grading run.
1.424     albertel 5028:              - downloading existing scan data (original, corrected
1.423     albertel 5029:                                                 or skipped info)
                   5030: 
                   5031:              - uploading new scan data
                   5032: 
                   5033:  Arguments:
                   5034:   $r          - The Apache request object
                   5035:   $file2grade - name of the file that contain the scanned data to score
                   5036: 
                   5037: =cut
1.186     albertel 5038: 
1.75      albertel 5039: sub scantron_selectphase {
1.209     ng       5040:     my ($r,$file2grade) = @_;
1.324     albertel 5041:     my ($symb)=&get_symb($r);
1.75      albertel 5042:     if (!$symb) {return '';}
1.423     albertel 5043:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 5044:     my $default_form_data=&defaultFormData($symb);
                   5045:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5046:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5047:     my $format_selector=&scantron_scantab();
1.186     albertel 5048:     my $CODE_selector=&scantron_CODElist();
                   5049:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5050:     my $result;
1.422     foxr     5051: 
1.513     foxr     5052:     $ssi_error = 0;
                   5053: 
1.422     foxr     5054:     # Chunk of form to prompt for a file to grade and how:
                   5055: 
1.489     albertel 5056:     $result.= '
                   5057:     <br />
                   5058:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5059:     <input type="hidden" name="command" value="scantron_warning" />
                   5060:     '.$default_form_data.'
                   5061:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5062:        '.&Apache::loncommon::start_data_table_header_row().'
                   5063:             <th colspan="2">
1.492     albertel 5064:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5065:             </th>
                   5066:        '.&Apache::loncommon::end_data_table_header_row().'
                   5067:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5068:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5069:        '.&Apache::loncommon::end_data_table_row().'
                   5070:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5071:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5072:        '.&Apache::loncommon::end_data_table_row().'
                   5073:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5074:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5075:        '.&Apache::loncommon::end_data_table_row().'
                   5076:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5077:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5078:        '.&Apache::loncommon::end_data_table_row().'
                   5079:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5080:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5081:        '.&Apache::loncommon::end_data_table_row().'
                   5082:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5083: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5084:             <td>
1.492     albertel 5085: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5086:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5087:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5088: 	    </td>
1.489     albertel 5089:        '.&Apache::loncommon::end_data_table_row().'
                   5090:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5091:             <td colspan="2">
1.572     www      5092:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5093:             </td>
1.489     albertel 5094:        '.&Apache::loncommon::end_data_table_row().'
                   5095:     '.&Apache::loncommon::end_data_table().'
                   5096:     </form>
                   5097: ';
1.162     albertel 5098:    
                   5099:     $r->print($result);
                   5100: 
1.257     albertel 5101:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5102:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5103: 
1.422     foxr     5104: 	# Chunk of form to prompt for a scantron file upload.
                   5105: 
1.489     albertel 5106:         $r->print('
                   5107:     <br />
                   5108:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5109:        '.&Apache::loncommon::start_data_table_header_row().'
                   5110:             <th>
1.572     www      5111:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
1.489     albertel 5112:             </th>
                   5113:        '.&Apache::loncommon::end_data_table_header_row().'
                   5114:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5115:             <td>
1.489     albertel 5116: ');
1.324     albertel 5117:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5118:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5119:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5120:     $r->print('
1.174     albertel 5121:               <script type="text/javascript" language="javascript">
                   5122:     function checkUpload(formname) {
                   5123: 	if (formname.upfile.value == "") {
1.492     albertel 5124: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5125: 	    return false;
                   5126: 	}
                   5127: 	formname.submit();
                   5128:     }
                   5129:               </script>
                   5130: 
1.492     albertel 5131:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5132:                 '.$default_form_data.'
                   5133:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5134:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5135:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5136:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5137:                 <br />
1.572     www      5138:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.174     albertel 5139:               </form>
1.492     albertel 5140: ');
1.162     albertel 5141: 
1.489     albertel 5142:         $r->print('
1.162     albertel 5143:             </td>
1.489     albertel 5144:        '.&Apache::loncommon::end_data_table_row().'
                   5145:        '.&Apache::loncommon::end_data_table().'
                   5146: ');
1.162     albertel 5147:     }
1.422     foxr     5148: 
                   5149:     # Chunk of the form that prompts to view a scoring office file,
                   5150:     # corrected file, skipped records in a file.
                   5151: 
1.489     albertel 5152:     $r->print('
                   5153:    <br />
                   5154:    <form action="/adm/grades" name="scantron_download">
                   5155:      '.$default_form_data.'
                   5156:      <input type="hidden" name="command" value="scantron_download" />
                   5157:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5158:        '.&Apache::loncommon::start_data_table_header_row().'
                   5159:               <th>
1.492     albertel 5160:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5161:               </th>
                   5162:        '.&Apache::loncommon::end_data_table_header_row().'
                   5163:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5164:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5165:                 <br />
1.492     albertel 5166:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5167:        '.&Apache::loncommon::end_data_table_row().'
                   5168:      '.&Apache::loncommon::end_data_table().'
                   5169:    </form>
                   5170:    <br />
                   5171: ');
1.162     albertel 5172: 
1.457     banghart 5173:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5174: 
1.528     raeburn  5175:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5176:              $default_form_data."\n".
                   5177:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5178:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5179:              '<th colspan="2">
1.572     www      5180:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5181:              '</th>'."\n".
                   5182:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5183:               &Apache::loncommon::start_data_table_row()."\n".
                   5184:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5185:               '<td> '.$sequence_selector.' </td>'.
                   5186:               &Apache::loncommon::end_data_table_row()."\n".
                   5187:               &Apache::loncommon::start_data_table_row()."\n".
                   5188:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5189:               '<td> '.$file_selector.' </td>'."\n".
                   5190:               &Apache::loncommon::end_data_table_row()."\n".
                   5191:               &Apache::loncommon::start_data_table_row()."\n".
                   5192:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5193:               '<td> '.$format_selector.' </td>'."\n".
                   5194:               &Apache::loncommon::end_data_table_row()."\n".
                   5195:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5196:               '<td> '.&mt('Options').' </td>'."\n".
                   5197:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5198:               &Apache::loncommon::end_data_table_row()."\n".
                   5199:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5200:               '<td colspan="2">'."\n".
                   5201:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575   ! www      5202:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5203:               '</td>'."\n".
                   5204:               &Apache::loncommon::end_data_table_row()."\n".
                   5205:               &Apache::loncommon::end_data_table()."\n".
                   5206:               '</form><br />');
1.457     banghart 5207:     $r->print($grading_menu_button);
1.523     raeburn  5208:     return;
1.75      albertel 5209: }
                   5210: 
1.423     albertel 5211: =pod
                   5212: 
                   5213: =item get_scantron_config
                   5214: 
                   5215:    Parse and return the scantron configuration line selected as a
                   5216:    hash of configuration file fields.
                   5217: 
                   5218:  Arguments:
                   5219:     which - the name of the configuration to parse from the file.
                   5220: 
                   5221: 
                   5222:  Returns:
                   5223:             If the named configuration is not in the file, an empty
                   5224:             hash is returned.
                   5225:     a hash with the fields
                   5226:       name         - internal name for the this configuration setup
                   5227:       description  - text to display to operator that describes this config
                   5228:       CODElocation - if 0 or the string 'none'
                   5229:                           - no CODE exists for this config
                   5230:                      if -1 || the string 'letter'
                   5231:                           - a CODE exists for this config and is
                   5232:                             a string of letters
                   5233:                      Unsupported value (but planned for future support)
                   5234:                           if a positive integer
                   5235:                                - The CODE exists as the first n items from
                   5236:                                  the question section of the form
                   5237:                           if the string 'number'
                   5238:                                - The CODE exists for this config and is
                   5239:                                  a string of numbers
                   5240:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5241:                      the CODE starts
                   5242:       CODElength  - length of the CODE
1.573     bisitz   5243:       IDstart     - column where the student/employee ID starts
1.556     weissno  5244:       IDlength    - length of the student/employee ID info
1.423     albertel 5245:       Qstart      - column where the information from the bubbled
                   5246:                     'questions' start
                   5247:       Qlength     - number of columns comprising a single bubble line from
                   5248:                     the sheet. (usually either 1 or 10)
1.424     albertel 5249:       Qon         - either a single character representing the character used
1.423     albertel 5250:                     to signal a bubble was chosen in the positional setup, or
                   5251:                     the string 'letter' if the letter of the chosen bubble is
                   5252:                     in the final, or 'number' if a number representing the
                   5253:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5254:       Qoff        - the character used to represent that a bubble was
                   5255:                     left blank
1.423     albertel 5256:       PaperID     - if the scanning process generates a unique number for each
                   5257:                     sheet scanned the column that this ID number starts in
                   5258:       PaperIDlength - number of columns that comprise the unique ID number
                   5259:                       for the sheet of paper
1.424     albertel 5260:       FirstName   - column that the first name starts in
1.423     albertel 5261:       FirstNameLength - number of columns that the first name spans
                   5262:  
                   5263:       LastName    - column that the last name starts in
                   5264:       LastNameLength - number of columns that the last name spans
                   5265: 
                   5266: =cut
1.422     foxr     5267: 
1.82      albertel 5268: sub get_scantron_config {
                   5269:     my ($which) = @_;
1.518     raeburn  5270:     my @lines = &get_scantronformat_file();
1.82      albertel 5271:     my %config;
1.157     albertel 5272:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5273:     foreach my $line (@lines) {
1.82      albertel 5274: 	my ($name,$descrip)=split(/:/,$line);
                   5275: 	if ($name ne $which ) { next; }
                   5276: 	chomp($line);
                   5277: 	my @config=split(/:/,$line);
                   5278: 	$config{'name'}=$config[0];
                   5279: 	$config{'description'}=$config[1];
                   5280: 	$config{'CODElocation'}=$config[2];
                   5281: 	$config{'CODEstart'}=$config[3];
                   5282: 	$config{'CODElength'}=$config[4];
                   5283: 	$config{'IDstart'}=$config[5];
                   5284: 	$config{'IDlength'}=$config[6];
                   5285: 	$config{'Qstart'}=$config[7];
1.497     foxr     5286:  	$config{'Qlength'}=$config[8];
1.82      albertel 5287: 	$config{'Qoff'}=$config[9];
                   5288: 	$config{'Qon'}=$config[10];
1.157     albertel 5289: 	$config{'PaperID'}=$config[11];
                   5290: 	$config{'PaperIDlength'}=$config[12];
                   5291: 	$config{'FirstName'}=$config[13];
                   5292: 	$config{'FirstNamelength'}=$config[14];
                   5293: 	$config{'LastName'}=$config[15];
                   5294: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5295: 	last;
                   5296:     }
                   5297:     return %config;
                   5298: }
                   5299: 
1.423     albertel 5300: =pod 
                   5301: 
                   5302: =item username_to_idmap
                   5303: 
1.556     weissno  5304:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5305:     student username:domain.
                   5306: 
                   5307:   Arguments:
                   5308: 
                   5309:     $classlist - reference to the class list hash. This is a hash
                   5310:                  keyed by student name:domain  whose elements are references
1.424     albertel 5311:                  to arrays containing various chunks of information
1.423     albertel 5312:                  about the student. (See loncoursedata for more info).
                   5313: 
                   5314:   Returns
                   5315:     %idmap - the constructed hash
                   5316: 
                   5317: =cut
                   5318: 
1.82      albertel 5319: sub username_to_idmap {
                   5320:     my ($classlist)= @_;
                   5321:     my %idmap;
                   5322:     foreach my $student (keys(%$classlist)) {
                   5323: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5324: 	    $student;
                   5325:     }
                   5326:     return %idmap;
                   5327: }
1.423     albertel 5328: 
                   5329: =pod
                   5330: 
1.424     albertel 5331: =item scantron_fixup_scanline
1.423     albertel 5332: 
                   5333:    Process a requested correction to a scanline.
                   5334: 
                   5335:   Arguments:
                   5336:     $scantron_config   - hash from &get_scantron_config()
                   5337:     $scan_data         - hash of correction information 
                   5338:                           (see &scantron_getfile())
                   5339:     $line              - existing scanline
                   5340:     $whichline         - line number of the passed in scanline
                   5341:     $field             - type of change to process 
                   5342:                          (either 
1.573     bisitz   5343:                           'ID'     -> correct the student/employee ID
1.423     albertel 5344:                           'CODE'   -> correct the CODE
                   5345:                           'answer' -> fixup the submitted answers)
                   5346:     
                   5347:    $args               - hash of additional info,
                   5348:                           - 'ID' 
                   5349:                                'newid' -> studentID to use in replacement
1.424     albertel 5350:                                           of existing one
1.423     albertel 5351:                           - 'CODE' 
                   5352:                                'CODE_ignore_dup' - set to true if duplicates
                   5353:                                                    should be ignored.
                   5354: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5355:                                         if the existing unfound code should
1.423     albertel 5356:                                         be used as is
                   5357:                           - 'answer'
                   5358:                                'response' - new answer or 'none' if blank
                   5359:                                'question' - the bubble line to change
1.503     raeburn  5360:                                'questionnum' - the question identifier,
                   5361:                                                may include subquestion. 
1.423     albertel 5362: 
                   5363:   Returns:
                   5364:     $line - the modified scanline
                   5365: 
                   5366:   Side effects: 
                   5367:     $scan_data - may be updated
                   5368: 
                   5369: =cut
                   5370: 
1.82      albertel 5371: 
1.157     albertel 5372: sub scantron_fixup_scanline {
                   5373:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5374:     if ($field eq 'ID') {
                   5375: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5376: 	    return ($line,1,'New value too large');
1.157     albertel 5377: 	}
                   5378: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5379: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5380: 				     $args->{'newid'});
                   5381: 	}
                   5382: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5383: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5384: 	if ($args->{'newid'}=~/^\s*$/) {
                   5385: 	    &scan_data($scan_data,"$whichline.user",
                   5386: 		       $args->{'username'}.':'.$args->{'domain'});
                   5387: 	}
1.186     albertel 5388:     } elsif ($field eq 'CODE') {
1.192     albertel 5389: 	if ($args->{'CODE_ignore_dup'}) {
                   5390: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5391: 	}
                   5392: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5393: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5394: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5395: 		return ($line,1,'New CODE value too large');
                   5396: 	    }
                   5397: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5398: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5399: 	    }
                   5400: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5401: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5402: 	}
1.157     albertel 5403:     } elsif ($field eq 'answer') {
1.497     foxr     5404: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5405: 	my $off=$scantron_config->{'Qoff'};
                   5406: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5407: 	my $answer=${off}x$length;
                   5408: 	if ($args->{'response'} eq 'none') {
                   5409: 	    &scan_data($scan_data,
1.503     raeburn  5410: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5411: 	} else {
                   5412: 	    if ($on eq 'letter') {
                   5413: 		my @alphabet=('A'..'Z');
                   5414: 		$answer=$alphabet[$args->{'response'}];
                   5415: 	    } elsif ($on eq 'number') {
                   5416: 		$answer=$args->{'response'}+1;
                   5417: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5418: 	    } else {
1.497     foxr     5419: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5420: 	    }
1.497     foxr     5421: 	    &scan_data($scan_data,
1.503     raeburn  5422: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5423: 	}
1.497     foxr     5424: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5425: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5426:     }
                   5427:     return $line;
                   5428: }
1.423     albertel 5429: 
                   5430: =pod
                   5431: 
                   5432: =item scan_data
                   5433: 
                   5434:     Edit or look up  an item in the scan_data hash.
                   5435: 
                   5436:   Arguments:
                   5437:     $scan_data  - The hash (see scantron_getfile)
                   5438:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5439:                   scantronfilename_key).
1.423     albertel 5440:     $data        - New value of the hash entry.
                   5441:     $delete      - If true, the entry is removed from the hash.
                   5442: 
                   5443:   Returns:
                   5444:     The new value of the hash table field (undefined if deleted).
                   5445: 
                   5446: =cut
                   5447: 
                   5448: 
1.157     albertel 5449: sub scan_data {
                   5450:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5451:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5452:     if (defined($value)) {
                   5453: 	$scan_data->{$filename.'_'.$key} = $value;
                   5454:     }
                   5455:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5456:     return $scan_data->{$filename.'_'.$key};
                   5457: }
1.423     albertel 5458: 
1.495     albertel 5459: # ----- These first few routines are general use routines.----
                   5460: 
                   5461: # Return the number of occurences of a pattern in a string.
                   5462: 
                   5463: sub occurence_count {
                   5464:     my ($string, $pattern) = @_;
                   5465: 
                   5466:     my @matches = ($string =~ /$pattern/g);
                   5467: 
                   5468:     return scalar(@matches);
                   5469: }
                   5470: 
                   5471: 
                   5472: # Take a string known to have digits and convert all the
                   5473: # digits into letters in the range J,A..I.
                   5474: 
                   5475: sub digits_to_letters {
                   5476:     my ($input) = @_;
                   5477: 
                   5478:     my @alphabet = ('J', 'A'..'I');
                   5479: 
                   5480:     my @input    = split(//, $input);
                   5481:     my $output ='';
                   5482:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5483: 	if ($input[$i] =~ /\d/) {
                   5484: 	    $output .= $alphabet[$input[$i]];
                   5485: 	} else {
                   5486: 	    $output .= $input[$i];
                   5487: 	}
                   5488:     }
                   5489:     return $output;
                   5490: }
                   5491: 
1.423     albertel 5492: =pod 
                   5493: 
                   5494: =item scantron_parse_scanline
                   5495: 
                   5496:   Decodes a scanline from the selected scantron file
                   5497: 
                   5498:  Arguments:
                   5499:     line             - The text of the scantron file line to process
                   5500:     whichline        - Line number
                   5501:     scantron_config  - Hash describing the format of the scantron lines.
                   5502:     scan_data        - Hash of extra information about the scanline
                   5503:                        (see scantron_getfile for more information)
                   5504:     just_header      - True if should not process question answers but only
                   5505:                        the stuff to the left of the answers.
                   5506:  Returns:
                   5507:    Hash containing the result of parsing the scanline
                   5508: 
                   5509:    Keys are all proceeded by the string 'scantron.'
                   5510: 
                   5511:        CODE    - the CODE in use for this scanline
                   5512:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5513:                  by the operator
                   5514:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5515:                             CODEs were selected, but the usage has been
                   5516:                             forced by the operator
1.556     weissno  5517:        ID  - student/employee ID
1.423     albertel 5518:        PaperID - if used, the ID number printed on the sheet when the 
                   5519:                  paper was scanned
                   5520:        FirstName - first name from the sheet
                   5521:        LastName  - last name from the sheet
                   5522: 
                   5523:      if just_header was not true these key may also exist
                   5524: 
1.447     foxr     5525:        missingerror - a list of bubble ranges that are considered to be answers
                   5526:                       to a single question that don't have any bubbles filled in.
                   5527:                       Of the form questionnumber:firstbubblenumber:count.
                   5528:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5529:                       to a single question that have more than one bubble filled in.
                   5530:                       Of the form questionnumber::firstbubblenumber:count
                   5531:    
                   5532:                 In the above, count is the number of bubble responses in the
                   5533:                 input line needed to represent the possible answers to the question.
                   5534:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5535:                 per line would have count = 2.
                   5536: 
1.423     albertel 5537:        maxquest     - the number of the last bubble line that was parsed
                   5538: 
                   5539:        (<number> starts at 1)
                   5540:        <number>.answer - zero or more letters representing the selected
                   5541:                          letters from the scanline for the bubble line 
                   5542:                          <number>.
                   5543:                          if blank there was either no bubble or there where
                   5544:                          multiple bubbles, (consult the keys missingerror and
                   5545:                          doubleerror if this is an error condition)
                   5546: 
                   5547: =cut
                   5548: 
1.82      albertel 5549: sub scantron_parse_scanline {
1.423     albertel 5550:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5551: 
1.82      albertel 5552:     my %record;
1.550     raeburn  5553:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5554:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5555:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5556:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5557: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5558: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5559: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5560: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5561: 	    $record{'scantron.CODE'}=substr($data,
                   5562: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5563: 					    $$scantron_config{'CODElength'});
1.191     albertel 5564: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5565: 		$record{'scantron.useCODE'}=1;
                   5566: 	    }
1.192     albertel 5567: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5568: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5569: 	    }
1.82      albertel 5570: 	} else {
                   5571: 	    #FIXME interpret first N questions
                   5572: 	}
                   5573:     }
1.83      albertel 5574:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5575: 				  $$scantron_config{'IDlength'});
1.157     albertel 5576:     $record{'scantron.PaperID'}=
                   5577: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5578: 	       $$scantron_config{'PaperIDlength'});
                   5579:     $record{'scantron.FirstName'}=
                   5580: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5581: 	       $$scantron_config{'FirstNamelength'});
                   5582:     $record{'scantron.LastName'}=
                   5583: 	substr($data,$$scantron_config{'LastName'}-1,
                   5584: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5585:     if ($just_header) { return \%record; }
1.194     albertel 5586: 
1.82      albertel 5587:     my @alphabet=('A'..'Z');
                   5588:     my $questnum=0;
1.447     foxr     5589:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5590: 
1.470     foxr     5591:     chomp($questions);		# Get rid of any trailing \n.
                   5592:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5593:     while (length($questions)) {
1.447     foxr     5594: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5595:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5596:                              || 1;
                   5597:         $questnum++;
                   5598:         my $quest_id = $questnum;
                   5599:         my $currentquest = substr($questions,0,$answer_length);
                   5600:         $questions       = substr($questions,$answer_length);
                   5601:         if (length($currentquest) < $answer_length) { next; }
                   5602: 
                   5603:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5604:             my $subquestnum = 1;
                   5605:             my $subquestions = $currentquest;
                   5606:             my @subanswers_needed = 
                   5607:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5608:             foreach my $subans (@subanswers_needed) {
                   5609:                 my $subans_length =
                   5610:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5611:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5612:                 $subquestions   = substr($subquestions,$subans_length);
                   5613:                 $quest_id = "$questnum.$subquestnum";
                   5614:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5615:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5616:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5617:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5618:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5619:                 } else {
                   5620:                     $ansnum = &scantron_validator_positional($ansnum,
                   5621:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5622:                 }
                   5623:                 $subquestnum ++;
                   5624:             }
                   5625:         } else {
                   5626:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5627:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5628:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5629:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5630:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5631:             } else {
                   5632:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5633:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5634:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5635:             }
                   5636:         }
                   5637:     }
                   5638:     $record{'scantron.maxquest'}=$questnum;
                   5639:     return \%record;
                   5640: }
1.447     foxr     5641: 
1.503     raeburn  5642: sub scantron_validator_lettnum {
                   5643:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5644:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5645: 
                   5646:     # Qon 'letter' implies for each slot in currquest we have:
                   5647:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5648:     #    about anything else (esp. a value of Qoff) for missing
                   5649:     #    bubbles.
                   5650:     #
                   5651:     # Qon 'number' implies each slot gives a digit that indexes the
                   5652:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5653:     #    and * or ? for double bubbles on a single line.
                   5654:     #
1.447     foxr     5655: 
1.503     raeburn  5656:     my $matchon;
                   5657:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5658:         $matchon = '[A-Z]';
                   5659:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5660:         $matchon = '\d';
                   5661:     }
                   5662:     my $occurrences = 0;
                   5663:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5664:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5665:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5666:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5667:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5668:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5669:         my @singlelines = split('',$currquest);
                   5670:         foreach my $entry (@singlelines) {
                   5671:             $occurrences = &occurence_count($entry,$matchon);
                   5672:             if ($occurrences > 1) {
                   5673:                 last;
                   5674:             }
                   5675:         } 
                   5676:     } else {
                   5677:         $occurrences = &occurence_count($currquest,$matchon); 
                   5678:     }
                   5679:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5680:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5681:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5682:             my $bubble = substr($currquest,$ans,1);
                   5683:             if ($bubble =~ /$matchon/ ) {
                   5684:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5685:                     if ($bubble == 0) {
                   5686:                         $bubble = 10; 
                   5687:                     }
                   5688:                     $record->{"scantron.$ansnum.answer"} = 
                   5689:                         $alphabet->[$bubble-1];
                   5690:                 } else {
                   5691:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5692:                 }
                   5693:             } else {
                   5694:                 $record->{"scantron.$ansnum.answer"}='';
                   5695:             }
                   5696:             $ansnum++;
                   5697:         }
                   5698:     } elsif (!defined($currquest)
                   5699:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5700:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5701:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5702:             $record->{"scantron.$ansnum.answer"}='';
                   5703:             $ansnum++;
                   5704:         }
                   5705:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5706:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5707:         }
                   5708:     } else {
                   5709:         if ($$scantron_config{'Qon'} eq 'number') {
                   5710:             $currquest = &digits_to_letters($currquest);            
                   5711:         }
                   5712:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5713:             my $bubble = substr($currquest,$ans,1);
                   5714:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5715:             $ansnum++;
                   5716:         }
                   5717:     }
                   5718:     return $ansnum;
                   5719: }
1.447     foxr     5720: 
1.503     raeburn  5721: sub scantron_validator_positional {
                   5722:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5723:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5724: 
1.503     raeburn  5725:     # Otherwise there's a positional notation;
                   5726:     # each bubble line requires Qlength items, and there are filled in
                   5727:     # bubbles for each case where there 'Qon' characters.
                   5728:     #
1.447     foxr     5729: 
1.503     raeburn  5730:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5731: 
1.503     raeburn  5732:     # If the split only gives us one element.. the full length of the
                   5733:     # answer string, no bubbles are filled in:
1.447     foxr     5734: 
1.507     raeburn  5735:     if ($answers_needed eq '') {
                   5736:         return;
                   5737:     }
                   5738: 
1.503     raeburn  5739:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5740:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5741:             $record->{"scantron.$ansnum.answer"}='';
                   5742:             $ansnum++;
                   5743:         }
                   5744:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5745:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5746:         }
                   5747:     } elsif (scalar(@array) == 2) {
                   5748:         my $location = length($array[0]);
                   5749:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5750:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5751:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5752:             if ($ans eq $line_num) {
                   5753:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5754:             } else {
                   5755:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5756:             }
                   5757:             $ansnum++;
                   5758:          }
                   5759:     } else {
                   5760:         #  If there's more than one instance of a bubble character
                   5761:         #  That's a double bubble; with positional notation we can
                   5762:         #  record all the bubbles filled in as well as the
                   5763:         #  fact this response consists of multiple bubbles.
                   5764:         #
                   5765:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5766:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5767:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5768:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5769:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5770:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5771:             my $doubleerror = 0;
                   5772:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5773:                    (!$doubleerror)) {
                   5774:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5775:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5776:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5777:                if (length(@currarray) > 2) {
                   5778:                    $doubleerror = 1;
                   5779:                } 
                   5780:             }
                   5781:             if ($doubleerror) {
                   5782:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5783:             }
                   5784:         } else {
                   5785:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5786:         }
                   5787:         my $item = $ansnum;
                   5788:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5789:             $record->{"scantron.$item.answer"} = '';
                   5790:             $item ++;
                   5791:         }
1.447     foxr     5792: 
1.503     raeburn  5793:         my @ans=@array;
                   5794:         my $i=0;
                   5795:         my $increment = 0;
                   5796:         while ($#ans) {
                   5797:             $i+=length($ans[0]) + $increment;
                   5798:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5799:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5800:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5801:             shift(@ans);
                   5802:             $increment = 1;
                   5803:         }
                   5804:         $ansnum += $answers_needed;
1.82      albertel 5805:     }
1.503     raeburn  5806:     return $ansnum;
1.82      albertel 5807: }
                   5808: 
1.423     albertel 5809: =pod
                   5810: 
                   5811: =item scantron_add_delay
                   5812: 
                   5813:    Adds an error message that occurred during the grading phase to a
                   5814:    queue of messages to be shown after grading pass is complete
                   5815: 
                   5816:  Arguments:
1.424     albertel 5817:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5818:    $scanline    - the scanline that caused the error
                   5819:    $errormesage - the error message
                   5820:    $errorcode   - a numeric code for the error
                   5821: 
                   5822:  Side Effects:
1.424     albertel 5823:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5824: 
                   5825: =cut
                   5826: 
1.82      albertel 5827: sub scantron_add_delay {
1.140     albertel 5828:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5829:     push(@$delayqueue,
                   5830: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5831: 	  'ecode' => $errorcode }
                   5832: 	 );
1.82      albertel 5833: }
                   5834: 
1.423     albertel 5835: =pod
                   5836: 
                   5837: =item scantron_find_student
                   5838: 
1.424     albertel 5839:    Finds the username for the current scanline
                   5840: 
                   5841:   Arguments:
                   5842:    $scantron_record - hash result from scantron_parse_scanline
                   5843:    $scan_data       - hash of correction information 
                   5844:                       (see &scantron_getfile() form more information)
                   5845:    $idmap           - hash from &username_to_idmap()
                   5846:    $line            - number of current scanline
                   5847:  
                   5848:   Returns:
                   5849:    Either 'username:domain' or undef if unknown
                   5850: 
1.423     albertel 5851: =cut
                   5852: 
1.82      albertel 5853: sub scantron_find_student {
1.157     albertel 5854:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5855:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5856:     if ($scanID =~ /^\s*$/) {
                   5857:  	return &scan_data($scan_data,"$line.user");
                   5858:     }
1.83      albertel 5859:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5860:  	if (lc($id) eq lc($scanID)) {
                   5861:  	    return $$idmap{$id};
                   5862:  	}
1.83      albertel 5863:     }
                   5864:     return undef;
                   5865: }
                   5866: 
1.423     albertel 5867: =pod
                   5868: 
                   5869: =item scantron_filter
                   5870: 
1.424     albertel 5871:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5872:    hidden resources was selected
                   5873: 
1.423     albertel 5874: =cut
                   5875: 
1.83      albertel 5876: sub scantron_filter {
                   5877:     my ($curres)=@_;
1.331     albertel 5878: 
                   5879:     if (ref($curres) && $curres->is_problem()) {
                   5880: 	# if the user has asked to not have either hidden
                   5881: 	# or 'randomout' controlled resources to be graded
                   5882: 	# don't include them
                   5883: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5884: 	    && $curres->randomout) {
                   5885: 	    return 0;
                   5886: 	}
1.83      albertel 5887: 	return 1;
                   5888:     }
                   5889:     return 0;
1.82      albertel 5890: }
                   5891: 
1.423     albertel 5892: =pod
                   5893: 
                   5894: =item scantron_process_corrections
                   5895: 
1.424     albertel 5896:    Gets correction information out of submitted form data and corrects
                   5897:    the scanline
                   5898: 
1.423     albertel 5899: =cut
                   5900: 
1.157     albertel 5901: sub scantron_process_corrections {
                   5902:     my ($r) = @_;
1.257     albertel 5903:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5904:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5905:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5906:     my $which=$env{'form.scantron_line'};
1.200     albertel 5907:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5908:     my ($skip,$err,$errmsg);
1.257     albertel 5909:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5910: 	$skip=1;
1.257     albertel 5911:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5912: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5913: 	    $env{'form.scantron_domain'};
1.157     albertel 5914: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5915: 	($line,$err,$errmsg)=
                   5916: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5917: 				     'ID',{'newid'=>$newid,
1.257     albertel 5918: 				    'username'=>$env{'form.scantron_username'},
                   5919: 				    'domain'=>$env{'form.scantron_domain'}});
                   5920:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5921: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5922: 	my $newCODE;
1.192     albertel 5923: 	my %args;
1.190     albertel 5924: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5925: 	    $newCODE='use_unfound';
1.190     albertel 5926: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5927: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5928: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5929: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5930: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5931: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5932: 	}
1.257     albertel 5933: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5934: 	    $args{'CODE_ignore_dup'}=1;
                   5935: 	}
                   5936: 	$args{'CODE'}=$newCODE;
1.186     albertel 5937: 	($line,$err,$errmsg)=
                   5938: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5939: 				     'CODE',\%args);
1.257     albertel 5940:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5941: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5942: 	    ($line,$err,$errmsg)=
                   5943: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5944: 					 $which,'answer',
                   5945: 					 { 'question'=>$question,
1.503     raeburn  5946: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   5947:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 5948: 	    if ($err) { last; }
                   5949: 	}
                   5950:     }
                   5951:     if ($err) {
1.398     albertel 5952: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5953:     } else {
1.200     albertel 5954: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5955: 	&scantron_putfile($scanlines,$scan_data);
                   5956:     }
                   5957: }
                   5958: 
1.423     albertel 5959: =pod
                   5960: 
                   5961: =item reset_skipping_status
                   5962: 
1.424     albertel 5963:    Forgets the current set of remember skipped scanlines (and thus
                   5964:    reverts back to considering all lines in the
                   5965:    scantron_skipped_<filename> file)
                   5966: 
1.423     albertel 5967: =cut
                   5968: 
1.200     albertel 5969: sub reset_skipping_status {
                   5970:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5971:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5972:     &scantron_putfile(undef,$scan_data);
                   5973: }
                   5974: 
1.423     albertel 5975: =pod
                   5976: 
                   5977: =item start_skipping
                   5978: 
1.424     albertel 5979:    Marks a scanline to be skipped. 
                   5980: 
1.423     albertel 5981: =cut
                   5982: 
1.376     albertel 5983: sub start_skipping {
1.200     albertel 5984:     my ($scan_data,$i)=@_;
                   5985:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5986:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5987: 	$remembered{$i}=2;
                   5988:     } else {
                   5989: 	$remembered{$i}=1;
                   5990:     }
1.200     albertel 5991:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5992: }
                   5993: 
1.423     albertel 5994: =pod
                   5995: 
                   5996: =item should_be_skipped
                   5997: 
1.424     albertel 5998:    Checks whether a scanline should be skipped.
                   5999: 
1.423     albertel 6000: =cut
                   6001: 
1.200     albertel 6002: sub should_be_skipped {
1.376     albertel 6003:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6004:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6005: 	# not redoing old skips
1.376     albertel 6006: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6007: 	return 0;
                   6008:     }
                   6009:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6010: 
                   6011:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6012: 	return 0;
                   6013:     }
1.200     albertel 6014:     return 1;
                   6015: }
                   6016: 
1.423     albertel 6017: =pod
                   6018: 
                   6019: =item remember_current_skipped
                   6020: 
1.424     albertel 6021:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6022:    file and remembers them into scan_data for later use.
                   6023: 
1.423     albertel 6024: =cut
                   6025: 
1.200     albertel 6026: sub remember_current_skipped {
                   6027:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6028:     my %to_remember;
                   6029:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6030: 	if ($scanlines->{'skipped'}[$i]) {
                   6031: 	    $to_remember{$i}=1;
                   6032: 	}
                   6033:     }
1.376     albertel 6034: 
1.200     albertel 6035:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6036:     &scantron_putfile(undef,$scan_data);
                   6037: }
                   6038: 
1.423     albertel 6039: =pod
                   6040: 
                   6041: =item check_for_error
                   6042: 
1.424     albertel 6043:     Checks if there was an error when attempting to remove a specific
                   6044:     scantron_.. bubble sheet data file. Prints out an error if
                   6045:     something went wrong.
                   6046: 
1.423     albertel 6047: =cut
                   6048: 
1.200     albertel 6049: sub check_for_error {
                   6050:     my ($r,$result)=@_;
                   6051:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6052: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6053:     }
                   6054: }
1.157     albertel 6055: 
1.423     albertel 6056: =pod
                   6057: 
                   6058: =item scantron_warning_screen
                   6059: 
1.424     albertel 6060:    Interstitial screen to make sure the operator has selected the
                   6061:    correct options before we start the validation phase.
                   6062: 
1.423     albertel 6063: =cut
                   6064: 
1.203     albertel 6065: sub scantron_warning_screen {
                   6066:     my ($button_text)=@_;
1.257     albertel 6067:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6068:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6069:     my $CODElist;
1.284     albertel 6070:     if ($scantron_config{'CODElocation'} &&
                   6071: 	$scantron_config{'CODEstart'} &&
                   6072: 	$scantron_config{'CODElength'}) {
                   6073: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6074: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6075: 	$CODElist=
1.492     albertel 6076: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6077: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6078:     }
1.492     albertel 6079:     return ('
1.203     albertel 6080: <p>
1.492     albertel 6081: <span class="LC_warning">
                   6082: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6083: </p>
                   6084: <table>
1.492     albertel 6085: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6086: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6087: '.$CODElist.'
1.203     albertel 6088: </table>
                   6089: <br />
1.492     albertel 6090: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6091: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6092: 
                   6093: <br />
1.492     albertel 6094: ');
1.203     albertel 6095: }
                   6096: 
1.423     albertel 6097: =pod
                   6098: 
                   6099: =item scantron_do_warning
                   6100: 
1.424     albertel 6101:    Check if the operator has picked something for all required
                   6102:    fields. Error out if something is missing.
                   6103: 
1.423     albertel 6104: =cut
                   6105: 
1.203     albertel 6106: sub scantron_do_warning {
                   6107:     my ($r)=@_;
1.324     albertel 6108:     my ($symb)=&get_symb($r);
1.203     albertel 6109:     if (!$symb) {return '';}
1.324     albertel 6110:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6111:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6112:     if ( $env{'form.selectpage'} eq '' ||
                   6113: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6114: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6115: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6116: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6117: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6118: 	} 
1.257     albertel 6119: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6120: 	    $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 6121: 	} 
1.257     albertel 6122: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6123: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
1.237     albertel 6124: 	} 
                   6125:     } else {
1.265     www      6126: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6127: 	$r->print('
                   6128: '.$warning.'
                   6129: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6130: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6131: ');
1.237     albertel 6132:     }
1.352     albertel 6133:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6134:     return '';
                   6135: }
                   6136: 
1.423     albertel 6137: =pod
                   6138: 
                   6139: =item scantron_form_start
                   6140: 
1.424     albertel 6141:     html hidden input for remembering all selected grading options
                   6142: 
1.423     albertel 6143: =cut
                   6144: 
1.203     albertel 6145: sub scantron_form_start {
                   6146:     my ($max_bubble)=@_;
                   6147:     my $result= <<SCANTRONFORM;
                   6148: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6149:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6150:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6151:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6152:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6153:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6154:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6155:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6156:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6157:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6158: SCANTRONFORM
1.447     foxr     6159: 
                   6160:   my $line = 0;
                   6161:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6162:        my $chunk =
                   6163: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6164:        $chunk .=
                   6165: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6166:        $chunk .= 
                   6167:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6168:        $chunk .=
                   6169:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6170:        $result .= $chunk;
                   6171:        $line++;
                   6172:    }
1.203     albertel 6173:     return $result;
                   6174: }
                   6175: 
1.423     albertel 6176: =pod
                   6177: 
                   6178: =item scantron_validate_file
                   6179: 
1.424     albertel 6180:     Dispatch routine for doing validation of a bubble sheet data file.
                   6181: 
                   6182:     Also processes any necessary information resets that need to
                   6183:     occur before validation begins (ignore previous corrections,
                   6184:     restarting the skipped records processing)
                   6185: 
1.423     albertel 6186: =cut
                   6187: 
1.157     albertel 6188: sub scantron_validate_file {
                   6189:     my ($r) = @_;
1.324     albertel 6190:     my ($symb)=&get_symb($r);
1.157     albertel 6191:     if (!$symb) {return '';}
1.324     albertel 6192:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6193:     
                   6194:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6195:     # them when doing the corrections reset
1.257     albertel 6196:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6197: 	&reset_skipping_status();
                   6198:     }
1.257     albertel 6199:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6200: 	&remember_current_skipped();
1.257     albertel 6201: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6202:     }
                   6203: 
1.257     albertel 6204:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6205: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6206: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6207: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6208: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6209:     }
1.200     albertel 6210: 
1.257     albertel 6211:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6212: 	&scantron_process_corrections($r);
                   6213:     }
1.503     raeburn  6214:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6215:     #get the student pick code ready
                   6216:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 6217:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 6218:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6219:     $r->print($result);
                   6220:     
1.334     albertel 6221:     my @validate_phases=( 'sequence',
                   6222: 			  'ID',
1.157     albertel 6223: 			  'CODE',
                   6224: 			  'doublebubble',
                   6225: 			  'missingbubbles');
1.257     albertel 6226:     if (!$env{'form.validatepass'}) {
                   6227: 	$env{'form.validatepass'} = 0;
1.157     albertel 6228:     }
1.257     albertel 6229:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6230: 
1.448     foxr     6231: 
1.157     albertel 6232:     my $stop=0;
                   6233:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6234: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6235: 	$r->rflush();
                   6236: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6237: 	{
                   6238: 	    no strict 'refs';
                   6239: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6240: 	}
                   6241:     }
                   6242:     if (!$stop) {
1.203     albertel 6243: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6244: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6245:                   $warning.
                   6246:                   &mt('Perform verification for each student after storage of submissions?').
                   6247:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6248:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6249:                   ('&nbsp;'x3).'<label>'.
                   6250:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6251:                   '</label></span><br />'.
                   6252:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6253:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
1.542     raeburn  6254:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6255:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6256:     } else {
                   6257: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6258: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6259:     }
                   6260:     if ($stop) {
1.334     albertel 6261: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6262: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6263: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6264: 
1.492     albertel 6265: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6266: 	} else {
1.503     raeburn  6267:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6268: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6269:             } else {
1.539     riegler  6270:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6271:             }
1.492     albertel 6272: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6273: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6274: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6275: 	}
1.157     albertel 6276:     }
1.352     albertel 6277:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6278:     return '';
                   6279: }
                   6280: 
1.423     albertel 6281: 
                   6282: =pod
                   6283: 
                   6284: =item scantron_remove_file
                   6285: 
1.424     albertel 6286:    Removes the requested bubble sheet data file, makes sure that
                   6287:    scantron_original_<filename> is never removed
                   6288: 
                   6289: 
1.423     albertel 6290: =cut
                   6291: 
1.200     albertel 6292: sub scantron_remove_file {
1.192     albertel 6293:     my ($which)=@_;
1.257     albertel 6294:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6295:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6296:     my $file='scantron_';
1.200     albertel 6297:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6298: 	$file.=$which.'_';
1.192     albertel 6299:     } else {
                   6300: 	return 'refused';
                   6301:     }
1.257     albertel 6302:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6303:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6304: }
                   6305: 
1.423     albertel 6306: 
                   6307: =pod
                   6308: 
                   6309: =item scantron_remove_scan_data
                   6310: 
1.424     albertel 6311:    Removes all scan_data correction for the requested bubble sheet
                   6312:    data file.  (In the case that both the are doing skipped records we need
                   6313:    to remember the old skipped lines for the time being so that element
                   6314:    persists for a while.)
                   6315: 
1.423     albertel 6316: =cut
                   6317: 
1.200     albertel 6318: sub scantron_remove_scan_data {
1.257     albertel 6319:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6320:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6321:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6322:     my @todelete;
1.257     albertel 6323:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6324:     foreach my $key (@keys) {
                   6325: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6326: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6327: 		$key=~/remember_skipping/) {
                   6328: 		next;
                   6329: 	    }
1.192     albertel 6330: 	    push(@todelete,$key);
                   6331: 	}
                   6332:     }
1.200     albertel 6333:     my $result;
1.192     albertel 6334:     if (@todelete) {
1.491     albertel 6335: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6336: 				       \@todelete,$cdom,$cname);
                   6337:     } else {
                   6338: 	$result = 'ok';
1.192     albertel 6339:     }
                   6340:     return $result;
                   6341: }
                   6342: 
1.423     albertel 6343: 
                   6344: =pod
                   6345: 
                   6346: =item scantron_getfile
                   6347: 
1.424     albertel 6348:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6349:     the scan_data hash
                   6350:   
                   6351:   Arguments:
                   6352:     None
                   6353: 
                   6354:   Returns:
                   6355:     2 hash references
                   6356: 
                   6357:      - first one has 
                   6358:          orig      -
                   6359:          corrected -
                   6360:          skipped   -  each of which points to an array ref of the specified
                   6361:                       file broken up into individual lines
                   6362:          count     - number of scanlines
                   6363:  
                   6364:      - second is the scan_data hash possible keys are
1.425     albertel 6365:        ($number refers to scanline numbered $number and thus the key affects
                   6366:         only that scanline
                   6367:         $bubline refers to the specific bubble line element and the aspects
                   6368:         refers to that specific bubble line element)
                   6369: 
                   6370:        $number.user - username:domain to use
                   6371:        $number.CODE_ignore_dup 
                   6372:                     - ignore the duplicate CODE error 
                   6373:        $number.useCODE
                   6374:                     - use the CODE in the scanline as is
                   6375:        $number.no_bubble.$bubline
                   6376:                     - it is valid that there is no bubbled in bubble
                   6377:                       at $number $bubline
                   6378:        remember_skipping
                   6379:                     - a frozen hash containing keys of $number and values
                   6380:                       of either 
                   6381:                         1 - we are on a 'do skipped records pass' and plan
                   6382:                             on processing this line
                   6383:                         2 - we are on a 'do skipped records pass' and this
                   6384:                             scanline has been marked to skip yet again
1.424     albertel 6385: 
1.423     albertel 6386: =cut
                   6387: 
1.157     albertel 6388: sub scantron_getfile {
1.200     albertel 6389:     #FIXME really would prefer a scantron directory
1.257     albertel 6390:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6391:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6392:     my $lines;
                   6393:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6394: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6395:     my %scanlines;
                   6396:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6397:     my $temp=$scanlines{'orig'};
                   6398:     $scanlines{'count'}=$#$temp;
                   6399: 
                   6400:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6401: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6402:     if ($lines eq '-1') {
                   6403: 	$scanlines{'corrected'}=[];
                   6404:     } else {
                   6405: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6406:     }
                   6407:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6408: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6409:     if ($lines eq '-1') {
                   6410: 	$scanlines{'skipped'}=[];
                   6411:     } else {
                   6412: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6413:     }
1.175     albertel 6414:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6415:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6416:     my %scan_data = @tmp;
                   6417:     return (\%scanlines,\%scan_data);
                   6418: }
                   6419: 
1.423     albertel 6420: =pod
                   6421: 
                   6422: =item lonnet_putfile
                   6423: 
1.424     albertel 6424:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6425: 
                   6426:  Arguments:
                   6427:    $contents - data to store
                   6428:    $filename - filename to store $contents into
                   6429: 
                   6430:  Returns:
                   6431:    result value from &Apache::lonnet::finishuserfileupload
                   6432: 
1.423     albertel 6433: =cut
                   6434: 
1.157     albertel 6435: sub lonnet_putfile {
                   6436:     my ($contents,$filename)=@_;
1.257     albertel 6437:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6438:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6439:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6440:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6441: 
                   6442: }
                   6443: 
1.423     albertel 6444: =pod
                   6445: 
                   6446: =item scantron_putfile
                   6447: 
1.424     albertel 6448:     Stores the current version of the bubble sheet data files, and the
                   6449:     scan_data hash. (Does not modify the original version only the
                   6450:     corrected and skipped versions.
                   6451: 
                   6452:  Arguments:
                   6453:     $scanlines - hash ref that looks like the first return value from
                   6454:                  &scantron_getfile()
                   6455:     $scan_data - hash ref that looks like the second return value from
                   6456:                  &scantron_getfile()
                   6457: 
1.423     albertel 6458: =cut
                   6459: 
1.157     albertel 6460: sub scantron_putfile {
                   6461:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6462:     #FIXME really would prefer a scantron directory
1.257     albertel 6463:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6464:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6465:     if ($scanlines) {
                   6466: 	my $prefix='scantron_';
1.157     albertel 6467: # no need to update orig, shouldn't change
                   6468: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6469: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6470: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6471: 			$prefix.'corrected_'.
1.257     albertel 6472: 			$env{'form.scantron_selectfile'});
1.200     albertel 6473: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6474: 			$prefix.'skipped_'.
1.257     albertel 6475: 			$env{'form.scantron_selectfile'});
1.200     albertel 6476:     }
1.175     albertel 6477:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6478: }
                   6479: 
1.423     albertel 6480: =pod
                   6481: 
                   6482: =item scantron_get_line
                   6483: 
1.424     albertel 6484:    Returns the correct version of the scanline
                   6485: 
                   6486:  Arguments:
                   6487:     $scanlines - hash ref that looks like the first return value from
                   6488:                  &scantron_getfile()
                   6489:     $scan_data - hash ref that looks like the second return value from
                   6490:                  &scantron_getfile()
                   6491:     $i         - number of the requested line (starts at 0)
                   6492: 
                   6493:  Returns:
                   6494:    A scanline, (either the original or the corrected one if it
                   6495:    exists), or undef if the requested scanline should be
                   6496:    skipped. (Either because it's an skipped scanline, or it's an
                   6497:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6498:    pass.
                   6499: 
1.423     albertel 6500: =cut
                   6501: 
1.157     albertel 6502: sub scantron_get_line {
1.200     albertel 6503:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6504:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6505:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6506:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6507:     return $scanlines->{'orig'}[$i]; 
                   6508: }
                   6509: 
1.423     albertel 6510: =pod
                   6511: 
                   6512: =item scantron_todo_count
                   6513: 
1.424     albertel 6514:     Counts the number of scanlines that need processing.
                   6515: 
                   6516:  Arguments:
                   6517:     $scanlines - hash ref that looks like the first return value from
                   6518:                  &scantron_getfile()
                   6519:     $scan_data - hash ref that looks like the second return value from
                   6520:                  &scantron_getfile()
                   6521: 
                   6522:  Returns:
                   6523:     $count - number of scanlines to process
                   6524: 
1.423     albertel 6525: =cut
                   6526: 
1.200     albertel 6527: sub get_todo_count {
                   6528:     my ($scanlines,$scan_data)=@_;
                   6529:     my $count=0;
                   6530:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6531: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6532: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6533: 	$count++;
                   6534:     }
                   6535:     return $count;
                   6536: }
                   6537: 
1.423     albertel 6538: =pod
                   6539: 
                   6540: =item scantron_put_line
                   6541: 
1.424     albertel 6542:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6543:     data file.
                   6544: 
                   6545:  Arguments:
                   6546:     $scanlines - hash ref that looks like the first return value from
                   6547:                  &scantron_getfile()
                   6548:     $scan_data - hash ref that looks like the second return value from
                   6549:                  &scantron_getfile()
                   6550:     $i         - line number to update
                   6551:     $newline   - contents of the updated scanline
                   6552:     $skip      - if true make the line for skipping and update the
                   6553:                  'skipped' file
                   6554: 
1.423     albertel 6555: =cut
                   6556: 
1.157     albertel 6557: sub scantron_put_line {
1.200     albertel 6558:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6559:     if ($skip) {
                   6560: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6561: 	&start_skipping($scan_data,$i);
1.157     albertel 6562: 	return;
                   6563:     }
                   6564:     $scanlines->{'corrected'}[$i]=$newline;
                   6565: }
                   6566: 
1.423     albertel 6567: =pod
                   6568: 
                   6569: =item scantron_clear_skip
                   6570: 
1.424     albertel 6571:    Remove a line from the 'skipped' file
                   6572: 
                   6573:  Arguments:
                   6574:     $scanlines - hash ref that looks like the first return value from
                   6575:                  &scantron_getfile()
                   6576:     $scan_data - hash ref that looks like the second return value from
                   6577:                  &scantron_getfile()
                   6578:     $i         - line number to update
                   6579: 
1.423     albertel 6580: =cut
                   6581: 
1.376     albertel 6582: sub scantron_clear_skip {
                   6583:     my ($scanlines,$scan_data,$i)=@_;
                   6584:     if (exists($scanlines->{'skipped'}[$i])) {
                   6585: 	undef($scanlines->{'skipped'}[$i]);
                   6586: 	return 1;
                   6587:     }
                   6588:     return 0;
                   6589: }
                   6590: 
1.423     albertel 6591: =pod
                   6592: 
                   6593: =item scantron_filter_not_exam
                   6594: 
1.424     albertel 6595:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6596:    filter out resources that are not marked as 'exam' mode
                   6597: 
1.423     albertel 6598: =cut
                   6599: 
1.334     albertel 6600: sub scantron_filter_not_exam {
                   6601:     my ($curres)=@_;
                   6602:     
                   6603:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6604: 	# if the user has asked to not have either hidden
                   6605: 	# or 'randomout' controlled resources to be graded
                   6606: 	# don't include them
                   6607: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6608: 	    && $curres->randomout) {
                   6609: 	    return 0;
                   6610: 	}
                   6611: 	return 1;
                   6612:     }
                   6613:     return 0;
                   6614: }
                   6615: 
1.423     albertel 6616: =pod
                   6617: 
                   6618: =item scantron_validate_sequence
                   6619: 
1.424     albertel 6620:     Validates the selected sequence, checking for resource that are
                   6621:     not set to exam mode.
                   6622: 
1.423     albertel 6623: =cut
                   6624: 
1.334     albertel 6625: sub scantron_validate_sequence {
                   6626:     my ($r,$currentphase) = @_;
                   6627: 
                   6628:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6629:     my (undef,undef,$sequence)=
                   6630: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6631: 
                   6632:     my $map=$navmap->getResourceByUrl($sequence);
                   6633: 
                   6634:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6635:                                     value="ignore" />');
                   6636:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6637: 	my @resources=
                   6638: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6639: 	if (@resources) {
1.357     banghart 6640: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
1.334     albertel 6641: 	    return (1,$currentphase);
                   6642: 	}
                   6643:     }
                   6644: 
                   6645:     return (0,$currentphase+1);
                   6646: }
                   6647: 
1.423     albertel 6648: 
                   6649: 
1.157     albertel 6650: sub scantron_validate_ID {
                   6651:     my ($r,$currentphase) = @_;
                   6652:     
                   6653:     #get student info
                   6654:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6655:     my %idmap=&username_to_idmap($classlist);
                   6656: 
                   6657:     #get scantron line setup
1.257     albertel 6658:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6659:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6660:     
                   6661:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6662: 
                   6663:     my %found=('ids'=>{},'usernames'=>{});
                   6664:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6665: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6666: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6667: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6668: 						 $scan_data);
                   6669: 	my $id=$$scan_record{'scantron.ID'};
                   6670: 	my $found;
                   6671: 	foreach my $checkid (keys(%idmap)) {
                   6672: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6673: 	}
                   6674: 	if ($found) {
                   6675: 	    my $username=$idmap{$found};
                   6676: 	    if ($found{'ids'}{$found}) {
                   6677: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6678: 					 $line,'duplicateID',$found);
1.194     albertel 6679: 		return(1,$currentphase);
1.157     albertel 6680: 	    } elsif ($found{'usernames'}{$username}) {
                   6681: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6682: 					 $line,'duplicateID',$username);
1.194     albertel 6683: 		return(1,$currentphase);
1.157     albertel 6684: 	    }
1.186     albertel 6685: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6686: 	    $found{'ids'}{$found}++;
                   6687: 	    $found{'usernames'}{$username}++;
                   6688: 	} else {
                   6689: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6690: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6691: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6692: 		    &scantron_get_correction($r,$i,$scan_record,
                   6693: 					     \%scantron_config,
                   6694: 					     $line,'duplicateID',$username);
1.194     albertel 6695: 		    return(1,$currentphase);
1.157     albertel 6696: 		} elsif (!defined($username)) {
                   6697: 		    &scantron_get_correction($r,$i,$scan_record,
                   6698: 					     \%scantron_config,
                   6699: 					     $line,'incorrectID');
1.194     albertel 6700: 		    return(1,$currentphase);
1.157     albertel 6701: 		}
                   6702: 		$found{'usernames'}{$username}++;
                   6703: 	    } else {
                   6704: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6705: 					 $line,'incorrectID');
1.194     albertel 6706: 		return(1,$currentphase);
1.157     albertel 6707: 	    }
                   6708: 	}
                   6709:     }
                   6710: 
                   6711:     return (0,$currentphase+1);
                   6712: }
                   6713: 
1.423     albertel 6714: 
1.157     albertel 6715: sub scantron_get_correction {
                   6716:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6717: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6718: #to show both the current line and the previous one and allow skipping
                   6719: #the previous one or the current one
                   6720: 
1.333     albertel 6721:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6722: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6723: 			    " for PaperID <tt>[_1]</tt>",
                   6724: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6725:     } else {
1.492     albertel 6726: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6727: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6728: 			    $i,$line)."</p> \n");
                   6729:     }
                   6730:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6731: 			  "The name on the paper is [_2],[_3]",
                   6732: 			  $$scan_record{'scantron.ID'},
                   6733: 			  $$scan_record{'scantron.LastName'},
                   6734: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6735: 
1.157     albertel 6736:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6737:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6738:                            # Array populated for doublebubble or
                   6739:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6740:                            # to validate radio button checking   
                   6741: 
1.157     albertel 6742:     if ($error =~ /ID$/) {
1.186     albertel 6743: 	if ($error eq 'incorrectID') {
1.492     albertel 6744: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6745: 		      "</p>\n");
1.157     albertel 6746: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6747: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6748: 	}
1.242     albertel 6749: 	$r->print($message);
1.492     albertel 6750: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6751: 	$r->print("\n<ul><li> ");
                   6752: 	#FIXME it would be nice if this sent back the user ID and
                   6753: 	#could do partial userID matches
                   6754: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6755: 				       'scantron_username','scantron_domain'));
                   6756: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6757: 	$r->print("\n@".
1.257     albertel 6758: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6759: 
                   6760: 	$r->print('</li>');
1.186     albertel 6761:     } elsif ($error =~ /CODE$/) {
                   6762: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6763: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6764: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6765: 	    $r->print("<p>".&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 6766: 	}
1.492     albertel 6767: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6768: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6769: 	$r->print($message);
1.492     albertel 6770: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6771: 	$r->print("\n<br /> ");
1.194     albertel 6772: 	my $i=0;
1.273     albertel 6773: 	if ($error eq 'incorrectCODE' 
                   6774: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6775: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6776: 	    if ($closest > 0) {
                   6777: 		foreach my $testcode (@{$closest}) {
                   6778: 		    my $checked='';
1.569     bisitz   6779: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6780: 		    $r->print("
                   6781:    <label>
1.569     bisitz   6782:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6783:        ".&mt("Use the similar CODE [_1] instead.",
                   6784: 	    "<b><tt>".$testcode."</tt></b>")."
                   6785:     </label>
                   6786:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6787: 		    $r->print("\n<br />");
                   6788: 		    $i++;
                   6789: 		}
1.194     albertel 6790: 	    }
                   6791: 	}
1.273     albertel 6792: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6793: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6794: 	    $r->print("
                   6795:     <label>
1.569     bisitz   6796:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6797:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6798: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6799:     </label>");
1.273     albertel 6800: 	    $r->print("\n<br />");
                   6801: 	}
1.194     albertel 6802: 
1.188     albertel 6803: 	$r->print(<<ENDSCRIPT);
                   6804: <script type="text/javascript">
                   6805: function change_radio(field) {
1.190     albertel 6806:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6807:     var i;
                   6808:     for (i=0;i<slct.length;i++) {
                   6809:         if (slct[i].value==field) { slct[i].checked=true; }
                   6810:     }
                   6811: }
                   6812: </script>
                   6813: ENDSCRIPT
1.187     albertel 6814: 	my $href="/adm/pickcode?".
1.359     www      6815: 	   "form=".&escape("scantronupload").
                   6816: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6817: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6818: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6819: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6820: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6821: 	    $r->print("
                   6822:     <label>
                   6823:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6824:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6825: 	     "<a target='_blank' href='$href'>","</a>")."
                   6826:     </label> 
1.558     bisitz   6827:     ".&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 6828: 	    $r->print("\n<br />");
                   6829: 	}
1.492     albertel 6830: 	$r->print("
                   6831:     <label>
                   6832:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6833:        ".&mt("Use [_1] as the CODE.",
                   6834: 	     "</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 6835: 	$r->print("\n<br /><br />");
1.157     albertel 6836:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6837: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6838: 
                   6839: 	# The form field scantron_questions is acutally a list of line numbers.
                   6840: 	# represented by this form so:
                   6841: 
                   6842: 	my $line_list = &questions_to_line_list($arg);
                   6843: 
1.157     albertel 6844: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6845: 		  $line_list.'" />');
1.242     albertel 6846: 	$r->print($message);
1.492     albertel 6847: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6848: 	foreach my $question (@{$arg}) {
1.503     raeburn  6849: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6850:                                                    $scan_record, $error);
1.524     raeburn  6851:             push(@lines_to_correct,@linenums);
1.157     albertel 6852: 	}
1.503     raeburn  6853:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6854:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6855: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6856: 	$r->print($message);
1.492     albertel 6857: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6858: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6859: 
1.503     raeburn  6860: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6861: 	# a list of question numbers. Therefore:
                   6862: 	#
                   6863: 	
                   6864: 	my $line_list = &questions_to_line_list($arg);
                   6865: 
1.157     albertel 6866: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6867: 		  $line_list.'" />');
1.157     albertel 6868: 	foreach my $question (@{$arg}) {
1.503     raeburn  6869: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6870:                                                    $scan_record, $error);
1.524     raeburn  6871:             push(@lines_to_correct,@linenums);
1.157     albertel 6872: 	}
1.503     raeburn  6873:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6874:     } else {
                   6875: 	$r->print("\n<ul>");
                   6876:     }
                   6877:     $r->print("\n</li></ul>");
1.497     foxr     6878: }
                   6879: 
1.503     raeburn  6880: sub verify_bubbles_checked {
                   6881:     my (@ansnums) = @_;
                   6882:     my $ansnumstr = join('","',@ansnums);
                   6883:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6884:     my $output = (<<ENDSCRIPT);
                   6885: <script type="text/javascript">
                   6886: function verify_bubble_radio(form) {
                   6887:     var ansnumArray = new Array ("$ansnumstr");
                   6888:     var need_bubble_count = 0;
                   6889:     for (var i=0; i<ansnumArray.length; i++) {
                   6890:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6891:             var bubble_picked = 0; 
                   6892:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6893:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6894:                     bubble_picked = 1;
                   6895:                 }
                   6896:             }
                   6897:             if (bubble_picked == 0) {
                   6898:                 need_bubble_count ++;
                   6899:             }
                   6900:         }
                   6901:     }
                   6902:     if (need_bubble_count) {
                   6903:         alert("$warning");
                   6904:         return;
                   6905:     }
                   6906:     form.submit(); 
                   6907: }
                   6908: </script>
                   6909: ENDSCRIPT
                   6910:     return $output;
                   6911: }
                   6912: 
1.497     foxr     6913: =pod
                   6914: 
                   6915: =item  questions_to_line_list
1.157     albertel 6916: 
1.497     foxr     6917: Converts a list of questions into a string of comma separated
                   6918: line numbers in the answer sheet used by the questions.  This is
                   6919: used to fill in the scantron_questions form field.
                   6920: 
                   6921:   Arguments:
                   6922:      questions    - Reference to an array of questions.
                   6923: 
                   6924: =cut
                   6925: 
                   6926: 
                   6927: sub questions_to_line_list {
                   6928:     my ($questions) = @_;
                   6929:     my @lines;
                   6930: 
1.503     raeburn  6931:     foreach my $item (@{$questions}) {
                   6932:         my $question = $item;
                   6933:         my ($first,$count,$last);
                   6934:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   6935:             $question = $1;
                   6936:             my $subquestion = $2;
                   6937:             $first = $first_bubble_line{$question-1} + 1;
                   6938:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6939:             my $subcount = 1;
                   6940:             while ($subcount<$subquestion) {
                   6941:                 $first += $subans[$subcount-1];
                   6942:                 $subcount ++;
                   6943:             }
                   6944:             $count = $subans[$subquestion-1];
                   6945:         } else {
                   6946: 	    $first   = $first_bubble_line{$question-1} + 1;
                   6947: 	    $count   = $bubble_lines_per_response{$question-1};
                   6948:         }
1.506     raeburn  6949:         $last = $first+$count-1;
1.503     raeburn  6950:         push(@lines, ($first..$last));
1.497     foxr     6951:     }
                   6952:     return join(',', @lines);
                   6953: }
                   6954: 
                   6955: =pod 
                   6956: 
                   6957: =item prompt_for_corrections
                   6958: 
                   6959: Prompts for a potentially multiline correction to the
                   6960: user's bubbling (factors out common code from scantron_get_correction
                   6961: for multi and missing bubble cases).
                   6962: 
                   6963:  Arguments:
                   6964:    $r           - Apache request object.
                   6965:    $question    - The question number to prompt for.
                   6966:    $scan_config - The scantron file configuration hash.
                   6967:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  6968:    $error       - Type of error
1.497     foxr     6969: 
                   6970:  Implicit inputs:
                   6971:    %bubble_lines_per_response   - Starting line numbers for each question.
                   6972:                                   Numbered from 0 (but question numbers are from
                   6973:                                   1.
                   6974:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  6975:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   6976:                                   type problems render as separate sub-questions, 
1.503     raeburn  6977:                                   in exam mode. This hash contains a 
                   6978:                                   comma-separated list of the lines per 
                   6979:                                   sub-question.
1.510     raeburn  6980:    %responsetype_per_response   - essayresponse, formularesponse,
                   6981:                                   stringresponse, imageresponse, reactionresponse,
                   6982:                                   and organicresponse type problem parts can have
1.503     raeburn  6983:                                   multiple lines per response if the weight
                   6984:                                   assigned exceeds 10.  In this case, only
                   6985:                                   one bubble per line is permitted, but more 
                   6986:                                   than one line might contain bubbles, e.g.
                   6987:                                   bubbling of: line 1 - J, line 2 - J, 
                   6988:                                   line 3 - B would assign 22 points.  
1.497     foxr     6989: 
                   6990: =cut
                   6991: 
                   6992: sub prompt_for_corrections {
1.503     raeburn  6993:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   6994:     my ($current_line,$lines);
                   6995:     my @linenums;
                   6996:     my $questionnum = $question;
                   6997:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   6998:         $question = $1;
                   6999:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7000:         my $subquestion = $2;
                   7001:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7002:         my $subcount = 1;
                   7003:         while ($subcount<$subquestion) {
                   7004:             $current_line += $subans[$subcount-1];
                   7005:             $subcount ++;
                   7006:         }
                   7007:         $lines = $subans[$subquestion-1];
                   7008:     } else {
                   7009:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7010:         $lines        = $bubble_lines_per_response{$question-1};
                   7011:     }
1.497     foxr     7012:     if ($lines > 1) {
1.503     raeburn  7013:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7014:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7015:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7016:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7017:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7018:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7019:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7020:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
1.503     raeburn  7021:         } else {
                   7022:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7023:         }
1.497     foxr     7024:     }
                   7025:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7026:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7027: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7028: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7029:         push(@linenums,$current_line);
1.497     foxr     7030: 	$current_line++;
                   7031:     }
                   7032:     if ($lines > 1) {
                   7033: 	$r->print("<hr /><br />");
                   7034:     }
1.503     raeburn  7035:     return @linenums;
1.157     albertel 7036: }
1.423     albertel 7037: 
                   7038: =pod
                   7039: 
                   7040: =item scantron_bubble_selector
                   7041:   
                   7042:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7043:    possibly showing the existing the selected bubbles if known
1.423     albertel 7044: 
                   7045:  Arguments:
                   7046:     $r           - Apache request object
                   7047:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7048:     $line        - Number of the line being displayed.
1.503     raeburn  7049:     $questionnum - Question number (may include subquestion)
                   7050:     $error       - Type of error.
1.497     foxr     7051:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7052: 
                   7053: =cut
                   7054: 
1.157     albertel 7055: sub scantron_bubble_selector {
1.503     raeburn  7056:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7057:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7058: 
                   7059:     my $scmode=$$scan_config{'Qon'};
                   7060:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7061: 
1.157     albertel 7062:     my @alphabet=('A'..'Z');
1.503     raeburn  7063:     $r->print(&Apache::loncommon::start_data_table().
                   7064:               &Apache::loncommon::start_data_table_row());
                   7065:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7066:     for (my $i=0;$i<$max+1;$i++) {
                   7067: 	$r->print("\n".'<td align="center">');
                   7068: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7069: 	else { $r->print('&nbsp;'); }
                   7070: 	$r->print('</td>');
                   7071:     }
1.503     raeburn  7072:     $r->print(&Apache::loncommon::end_data_table_row().
                   7073:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7074:     for (my $i=0;$i<$max;$i++) {
                   7075: 	$r->print("\n".
                   7076: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7077: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7078:     }
1.503     raeburn  7079:     my $nobub_checked = ' ';
                   7080:     if ($error eq 'missingbubble') {
                   7081:         $nobub_checked = ' checked = "checked" ';
                   7082:     }
                   7083:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7084: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7085:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7086:               $line.'" value="'.$questionnum.'" /></td>');
                   7087:     $r->print(&Apache::loncommon::end_data_table_row().
                   7088:               &Apache::loncommon::end_data_table());
1.157     albertel 7089: }
                   7090: 
1.423     albertel 7091: =pod
                   7092: 
                   7093: =item num_matches
                   7094: 
1.424     albertel 7095:    Counts the number of characters that are the same between the two arguments.
                   7096: 
                   7097:  Arguments:
                   7098:    $orig - CODE from the scanline
                   7099:    $code - CODE to match against
                   7100: 
                   7101:  Returns:
                   7102:    $count - integer count of the number of same characters between the
                   7103:             two arguments
                   7104: 
1.423     albertel 7105: =cut
                   7106: 
1.194     albertel 7107: sub num_matches {
                   7108:     my ($orig,$code) = @_;
                   7109:     my @code=split(//,$code);
                   7110:     my @orig=split(//,$orig);
                   7111:     my $same=0;
                   7112:     for (my $i=0;$i<scalar(@code);$i++) {
                   7113: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7114:     }
                   7115:     return $same;
                   7116: }
                   7117: 
1.423     albertel 7118: =pod
                   7119: 
                   7120: =item scantron_get_closely_matching_CODEs
                   7121: 
1.424     albertel 7122:    Cycles through all CODEs and finds the set that has the greatest
                   7123:    number of same characters as the provided CODE
                   7124: 
                   7125:  Arguments:
                   7126:    $allcodes - hash ref returned by &get_codes()
                   7127:    $CODE     - CODE from the current scanline
                   7128: 
                   7129:  Returns:
                   7130:    2 element list
                   7131:     - first elements is number of how closely matching the best fit is 
                   7132:       (5 means best set has 5 matching characters)
                   7133:     - second element is an arrary ref containing the set of valid CODEs
                   7134:       that best fit the passed in CODE
                   7135: 
1.423     albertel 7136: =cut
                   7137: 
1.194     albertel 7138: sub scantron_get_closely_matching_CODEs {
                   7139:     my ($allcodes,$CODE)=@_;
                   7140:     my @CODEs;
                   7141:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7142: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7143:     }
                   7144: 
                   7145:     return ($#CODEs,$CODEs[-1]);
                   7146: }
                   7147: 
1.423     albertel 7148: =pod
                   7149: 
                   7150: =item get_codes
                   7151: 
1.424     albertel 7152:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7153:    set of remembered CODEs.
                   7154: 
                   7155:  Arguments:
                   7156:   $old_name - name of the set of remembered CODEs
                   7157:   $cdom     - domain of the course
                   7158:   $cnum     - internal course name
                   7159: 
                   7160:  Returns:
                   7161:   %allcodes - keys are the valid CODEs, values are all 1
                   7162: 
1.423     albertel 7163: =cut
                   7164: 
1.194     albertel 7165: sub get_codes {
1.280     foxr     7166:     my ($old_name, $cdom, $cnum) = @_;
                   7167:     if (!$old_name) {
                   7168: 	$old_name=$env{'form.scantron_CODElist'};
                   7169:     }
                   7170:     if (!$cdom) {
                   7171: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7172:     }
                   7173:     if (!$cnum) {
                   7174: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7175:     }
1.278     albertel 7176:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7177: 				    $cdom,$cnum);
                   7178:     my %allcodes;
                   7179:     if ($result{"type\0$old_name"} eq 'number') {
                   7180: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7181:     } else {
                   7182: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7183:     }
1.194     albertel 7184:     return %allcodes;
                   7185: }
                   7186: 
1.423     albertel 7187: =pod
                   7188: 
                   7189: =item scantron_validate_CODE
                   7190: 
1.424     albertel 7191:    Validates all scanlines in the selected file to not have any
                   7192:    invalid or underspecified CODEs and that none of the codes are
                   7193:    duplicated if this was requested.
                   7194: 
1.423     albertel 7195: =cut
                   7196: 
1.157     albertel 7197: sub scantron_validate_CODE {
                   7198:     my ($r,$currentphase) = @_;
1.257     albertel 7199:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7200:     if ($scantron_config{'CODElocation'} &&
                   7201: 	$scantron_config{'CODEstart'} &&
                   7202: 	$scantron_config{'CODElength'}) {
1.257     albertel 7203: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7204: 	    &FIXME_blow_up()
                   7205: 	}
                   7206:     } else {
                   7207: 	return (0,$currentphase+1);
                   7208:     }
                   7209:     
                   7210:     my %usedCODEs;
                   7211: 
1.194     albertel 7212:     my %allcodes=&get_codes();
1.186     albertel 7213: 
1.447     foxr     7214:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   7215: 
1.186     albertel 7216:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7217:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7218: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7219: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7220: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7221: 						 $scan_data);
                   7222: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7223: 	my $error=0;
1.224     albertel 7224: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7225: 	    &scantron_get_correction($r,$i,$scan_record,
                   7226: 				     \%scantron_config,
                   7227: 				     $line,'incorrectCODE',\%allcodes);
                   7228: 	    return(1,$currentphase);
                   7229: 	}
1.221     albertel 7230: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7231: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7232: 	    &scantron_get_correction($r,$i,$scan_record,
                   7233: 				     \%scantron_config,
1.194     albertel 7234: 				     $line,'incorrectCODE',\%allcodes);
                   7235: 	    return(1,$currentphase);
1.186     albertel 7236: 	}
1.214     albertel 7237: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7238: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7239: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7240: 	    &scantron_get_correction($r,$i,$scan_record,
                   7241: 				     \%scantron_config,
1.194     albertel 7242: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7243: 	    return(1,$currentphase);
1.186     albertel 7244: 	}
1.524     raeburn  7245: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7246:     }
1.157     albertel 7247:     return (0,$currentphase+1);
                   7248: }
                   7249: 
1.423     albertel 7250: =pod
                   7251: 
                   7252: =item scantron_validate_doublebubble
                   7253: 
1.424     albertel 7254:    Validates all scanlines in the selected file to not have any
                   7255:    bubble lines with multiple bubbles marked.
                   7256: 
1.423     albertel 7257: =cut
                   7258: 
1.157     albertel 7259: sub scantron_validate_doublebubble {
                   7260:     my ($r,$currentphase) = @_;
                   7261:     #get student info
                   7262:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7263:     my %idmap=&username_to_idmap($classlist);
                   7264: 
                   7265:     #get scantron line setup
1.257     albertel 7266:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7267:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     7268:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   7269: 
1.157     albertel 7270:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7271: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7272: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7273: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7274: 						 $scan_data);
                   7275: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7276: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7277: 				 'doublebubble',
                   7278: 				 $$scan_record{'scantron.doubleerror'});
                   7279:     	return (1,$currentphase);
                   7280:     }
                   7281:     return (0,$currentphase+1);
                   7282: }
                   7283: 
1.423     albertel 7284: 
1.503     raeburn  7285: sub scantron_get_maxbubble {
1.257     albertel 7286:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7287: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7288: 	&restore_bubble_lines();
1.257     albertel 7289: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7290:     }
1.330     albertel 7291: 
1.447     foxr     7292:     my (undef, undef, $sequence) =
1.257     albertel 7293: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7294: 
1.447     foxr     7295:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 7296:     my $map=$navmap->getResourceByUrl($sequence);
                   7297:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7298: 
                   7299:     &Apache::lonxml::clear_problem_counter();
                   7300: 
1.557     raeburn  7301:     my $uname       = $env{'user.name'};
                   7302:     my $udom        = $env{'user.domain'};
1.435     foxr     7303:     my $cid         = $env{'request.course.id'};
                   7304:     my $total_lines = 0;
                   7305:     %bubble_lines_per_response = ();
1.447     foxr     7306:     %first_bubble_line         = ();
1.503     raeburn  7307:     %subdivided_bubble_lines   = ();
                   7308:     %responsetype_per_response = ();
1.554     raeburn  7309: 
1.447     foxr     7310:     my $response_number = 0;
                   7311:     my $bubble_line     = 0;
1.191     albertel 7312:     foreach my $resource (@resources) {
1.542     raeburn  7313:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7314:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7315: 	    foreach my $part_id (@{$parts}) {
                   7316:                 my $lines;
                   7317: 
                   7318: 	        # TODO - make this a persistent hash not an array.
                   7319: 
                   7320:                 # optionresponse, matchresponse and rankresponse type items 
                   7321:                 # render as separate sub-questions in exam mode.
                   7322:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7323:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7324:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7325:                     my ($numbub,$numshown);
                   7326:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7327:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7328:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7329:                         }
                   7330:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7331:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7332:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7333:                         }
                   7334:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7335:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7336:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7337:                         }
                   7338:                     }
                   7339:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7340:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7341:                     }
                   7342:                     my $bubbles_per_line = 10;
                   7343:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7344:                     if (($numbub % $bubbles_per_line) != 0) {
                   7345:                         $inner_bubble_lines++;
                   7346:                     }
                   7347:                     for (my $i=0; $i<$numshown; $i++) {
                   7348:                         $subdivided_bubble_lines{$response_number} .= 
                   7349:                             $inner_bubble_lines.',';
                   7350:                     }
                   7351:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7352:                     $lines = $numshown * $inner_bubble_lines;
                   7353:                 } else {
                   7354:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7355:                 } 
                   7356: 
                   7357:                 $first_bubble_line{$response_number} = $bubble_line;
                   7358: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7359:                 $responsetype_per_response{$response_number} = 
                   7360:                     $analysis->{$part_id.'.type'};
                   7361: 	        $response_number++;
                   7362: 
                   7363: 	        $bubble_line +=  $lines;
                   7364: 	        $total_lines +=  $lines;
                   7365: 	    }
                   7366:         }
                   7367:     }
1.552     raeburn  7368:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7369: 
                   7370:     &save_bubble_lines();
                   7371:     $env{'form.scantron_maxbubble'} =
                   7372: 	$total_lines;
                   7373:     return $env{'form.scantron_maxbubble'};
                   7374: }
1.523     raeburn  7375: 
1.157     albertel 7376: sub scantron_validate_missingbubbles {
                   7377:     my ($r,$currentphase) = @_;
                   7378:     #get student info
                   7379:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7380:     my %idmap=&username_to_idmap($classlist);
                   7381: 
                   7382:     #get scantron line setup
1.257     albertel 7383:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7384:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7385:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7386:     if (!$max_bubble) { $max_bubble=2**31; }
                   7387:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7388: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7389: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7390: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7391: 						 $scan_data);
                   7392: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7393: 	my @to_correct;
1.470     foxr     7394: 	
                   7395: 	# Probably here's where the error is...
                   7396: 
1.157     albertel 7397: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7398:             my $lastbubble;
                   7399:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7400:                my $question = $1;
                   7401:                my $subquestion = $2;
                   7402:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7403:                my $first = $first_bubble_line{$question-1};
                   7404:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7405:                my $subcount = 1;
                   7406:                while ($subcount<$subquestion) {
                   7407:                    $first += $subans[$subcount-1];
                   7408:                    $subcount ++;
                   7409:                }
                   7410:                my $count = $subans[$subquestion-1];
                   7411:                $lastbubble = $first + $count;
                   7412:             } else {
                   7413:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7414:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7415:             }
                   7416:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7417: 	    push(@to_correct,$missing);
                   7418: 	}
                   7419: 	if (@to_correct) {
                   7420: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7421: 				     $line,'missingbubble',\@to_correct);
                   7422: 	    return (1,$currentphase);
                   7423: 	}
                   7424: 
                   7425:     }
                   7426:     return (0,$currentphase+1);
                   7427: }
                   7428: 
1.423     albertel 7429: 
1.82      albertel 7430: sub scantron_process_students {
1.75      albertel 7431:     my ($r) = @_;
1.513     foxr     7432: 
1.257     albertel 7433:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7434:     my ($symb)=&get_symb($r);
1.513     foxr     7435:     if (!$symb) {
                   7436: 	return '';
                   7437:     }
1.324     albertel 7438:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7439: 
1.257     albertel 7440:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7441:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7442:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7443:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7444:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7445:     my $map=$navmap->getResourceByUrl($sequence);
                   7446:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7447:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7448:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7449:                             \%grader_randomlists_by_symb);
                   7450:     foreach my $resource (@resources) {
                   7451:         my $ressymb = $resource->symb();
                   7452:         my ($analysis,$parts) =
                   7453:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7454:                                       $env{'user.name'},$env{'user.domain'},1);
                   7455:         $grader_partids_by_symb{$ressymb} = $parts;
                   7456:         if (ref($analysis) eq 'HASH') {
                   7457:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7458:                 $grader_randomlists_by_symb{$ressymb} = 
                   7459:                     $analysis->{'parts_withrandomlist'};
                   7460:             }
                   7461:         }
                   7462:     }
                   7463: 
1.554     raeburn  7464:     my ($uname,$udom);
1.82      albertel 7465:     my $result= <<SCANTRONFORM;
1.81      albertel 7466: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7467:   <input type="hidden" name="command" value="scantron_configphase" />
                   7468:   $default_form_data
                   7469: SCANTRONFORM
1.82      albertel 7470:     $r->print($result);
                   7471: 
                   7472:     my @delayqueue;
1.542     raeburn  7473:     my (%completedstudents,%scandata);
1.140     albertel 7474:     
1.520     www      7475:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7476:     my $count=&get_todo_count($scanlines,$scan_data);
1.575   ! www      7477:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
        !          7478:  				    'Bubblesheet Progress',$count,
1.195     albertel 7479: 				    'inline',undef,'scantronupload');
1.140     albertel 7480:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7481: 					  'Processing first student');
1.542     raeburn  7482:     $r->print('<br />');
1.140     albertel 7483:     my $start=&Time::HiRes::time();
1.158     albertel 7484:     my $i=-1;
1.542     raeburn  7485:     my $started;
1.447     foxr     7486: 
                   7487:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
1.513     foxr     7488: 
                   7489:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7490:     # the user and return.
                   7491: 
                   7492:     if ($ssi_error) {
                   7493: 	$r->print("</form>");
                   7494: 	&ssi_print_error($r);
                   7495: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7496:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7497: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7498:     }
1.447     foxr     7499: 
1.542     raeburn  7500:     my %lettdig = &letter_to_digits();
                   7501:     my $numletts = scalar(keys(%lettdig));
                   7502: 
1.157     albertel 7503:     while ($i<$scanlines->{'count'}) {
                   7504:  	($uname,$udom)=('','');
                   7505:  	$i++;
1.200     albertel 7506:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7507:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7508: 	if ($started) {
                   7509: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7510: 						     'last student');
                   7511: 	}
                   7512: 	$started=1;
1.157     albertel 7513:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7514:  						 $scan_data);
                   7515:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7516:  					      \%idmap,$i)) {
                   7517:   	    &scantron_add_delay(\@delayqueue,$line,
                   7518:  				'Unable to find a student that matches',1);
                   7519:  	    next;
                   7520:   	}
                   7521:  	if (exists $completedstudents{$uname}) {
                   7522:  	    &scantron_add_delay(\@delayqueue,$line,
                   7523:  				'Student '.$uname.' has multiple sheets',2);
                   7524:  	    next;
                   7525:  	}
                   7526:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7527: 
1.554     raeburn  7528:         my %partids_by_symb;
                   7529:         foreach my $resource (@resources) {
                   7530:             my $ressymb = $resource->symb();
1.557     raeburn  7531:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7532:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7533:                 my ($analysis,$parts) =
                   7534:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7535:                 $partids_by_symb{$ressymb} = $parts;
                   7536:             } else {
                   7537:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7538:             }
1.554     raeburn  7539:         }
                   7540: 
1.330     albertel 7541: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7542:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7543: 
                   7544: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7545: 	    &scantron_putfile($scanlines,$scan_data);
                   7546: 	}
1.161     albertel 7547: 	
1.542     raeburn  7548:         my $scancode;
                   7549:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7550:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7551:             $scancode = $scan_record->{'scantron.CODE'};
                   7552:         } else {
                   7553:             $scancode = '';
                   7554:         }
                   7555: 
                   7556:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7557:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7558:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7559:             $r->print("</form>");
                   7560:             &ssi_print_error($r);
                   7561:             $r->print(&show_grading_menu_form($symb));
                   7562:             &Apache::lonnet::remove_lock($lock);
                   7563:             return '';      # Why return ''?  Beats me.
                   7564:         }
1.513     foxr     7565: 
1.140     albertel 7566: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7567:         if ($env{'form.verifyrecord'}) {
                   7568:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7569:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7570:             chomp($studentdata);
                   7571:             $studentdata =~ s/\r$//;
                   7572:             my $studentrecord = '';
                   7573:             my $counter = -1;
                   7574:             foreach my $resource (@resources) {
1.554     raeburn  7575:                 my $ressymb = $resource->symb();
1.542     raeburn  7576:                 ($counter,my $recording) =
                   7577:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7578:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7579:                                              \%scantron_config,\%lettdig,$numletts);
                   7580:                 $studentrecord .= $recording;
                   7581:             }
                   7582:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7583:                 &Apache::lonxml::clear_problem_counter();
                   7584:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7585:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7586:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7587:                     $r->print("</form>");
                   7588:                     &ssi_print_error($r);
                   7589:                     $r->print(&show_grading_menu_form($symb));
                   7590:                     &Apache::lonnet::remove_lock($lock);
                   7591:                     delete($completedstudents{$uname});
                   7592:                     return '';
                   7593:                 }
1.542     raeburn  7594:                 $counter = -1;
                   7595:                 $studentrecord = '';
                   7596:                 foreach my $resource (@resources) {
1.554     raeburn  7597:                     my $ressymb = $resource->symb();
1.542     raeburn  7598:                     ($counter,my $recording) =
                   7599:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7600:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7601:                                                  \%scantron_config,\%lettdig,$numletts);
                   7602:                     $studentrecord .= $recording;
                   7603:                 }
                   7604:                 if ($studentrecord ne $studentdata) {
                   7605:                     $r->print('<p><span class="LC_error">');
                   7606:                     if ($scancode eq '') {
                   7607:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7608:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7609:                     } else {
                   7610:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7611:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7612:                     }
                   7613:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7614:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7615:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7616:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7617:                               &Apache::loncommon::start_data_table_row().
                   7618:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7619:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7620:                               &Apache::loncommon::end_data_table_row().
                   7621:                               &Apache::loncommon::start_data_table_row().
                   7622:                               '<td>Stored submissions</td>'.
                   7623:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7624:                               &Apache::loncommon::end_data_table_row().
                   7625:                               &Apache::loncommon::end_data_table().'</p>');
                   7626:                 } else {
                   7627:                     $r->print('<br /><span class="LC_warning">'.
                   7628:                              &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 />'.
                   7629:                              &mt("As a consequence, this user's submission history records two tries.").
                   7630:                                  '</span><br />');
                   7631:                 }
                   7632:             }
                   7633:         }
1.543     raeburn  7634:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7635:     } continue {
1.330     albertel 7636: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7637: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7638:     }
1.140     albertel 7639:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7640:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7641: #    my $lasttime = &Time::HiRes::time()-$start;
                   7642: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7643: 
1.200     albertel 7644:     $r->print("</form>");
1.324     albertel 7645:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7646:     return '';
1.75      albertel 7647: }
1.157     albertel 7648: 
1.557     raeburn  7649: sub graders_resources_pass {
                   7650:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7651:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7652:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7653:         foreach my $resource (@{$resources}) {
                   7654:             my $ressymb = $resource->symb();
                   7655:             my ($analysis,$parts) =
                   7656:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7657:                                           $env{'user.name'},$env{'user.domain'},1);
                   7658:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7659:             if (ref($analysis) eq 'HASH') {
                   7660:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7661:                     $grader_randomlists_by_symb->{$ressymb} =
                   7662:                         $analysis->{'parts_withrandomlist'};
                   7663:                 }
                   7664:             }
                   7665:         }
                   7666:     }
                   7667:     return;
                   7668: }
                   7669: 
1.542     raeburn  7670: sub grade_student_bubbles {
1.554     raeburn  7671:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7672:     if (ref($resources) eq 'ARRAY') {
                   7673:         my $count = 0;
                   7674:         foreach my $resource (@{$resources}) {
                   7675:             my $ressymb = $resource->symb();
                   7676:             my %form = ('submitted'      => 'scantron',
                   7677:                         'grade_target'   => 'grade',
                   7678:                         'grade_username' => $uname,
                   7679:                         'grade_domain'   => $udom,
                   7680:                         'grade_courseid' => $env{'request.course.id'},
                   7681:                         'grade_symb'     => $ressymb,
                   7682:                         'CODE'           => $scancode
                   7683:                        );
                   7684:             if (ref($parts) eq 'HASH') {
                   7685:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7686:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7687:                         $form{'scantron_questnum_start.'.$part} =
                   7688:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7689:                         $count++;
                   7690:                     }
                   7691:                 }
                   7692:             }
                   7693:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7694:             return 'ssi_error' if ($ssi_error);
                   7695:             last if (&Apache::loncommon::connection_aborted($r));
                   7696:         }
1.542     raeburn  7697:     }
                   7698:     return;
                   7699: }
                   7700: 
1.157     albertel 7701: sub scantron_upload_scantron_data {
                   7702:     my ($r)=@_;
1.565     raeburn  7703:     my $dom = $env{'request.role.domain'};
                   7704:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7705:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7706:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7707: 							  'domainid',
1.565     raeburn  7708: 							  'coursename',$dom);
                   7709:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7710:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 7711:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7712:     $r->print('
1.157     albertel 7713: <script type="text/javascript" language="javascript">
                   7714:     function checkUpload(formname) {
                   7715: 	if (formname.upfile.value == "") {
1.539     riegler  7716: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.157     albertel 7717: 	    return false;
                   7718: 	}
1.565     raeburn  7719:         if (formname.courseid.value == "") {
                   7720:             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.').'");
                   7721:             return false;
                   7722:         }
1.157     albertel 7723: 	formname.submit();
                   7724:     }
1.565     raeburn  7725: 
                   7726:     function ToSyllabus() {
                   7727:         var cdom = '."'$dom'".';
                   7728:         var cnum = document.rules.courseid.value;
                   7729:         if (cdom == "" || cdom == null) {
                   7730:             return;
                   7731:         }
                   7732:         if (cnum == "" || cnum == null) {
                   7733:            return;
                   7734:         }
                   7735:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7736:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7737:         return;
                   7738:     }
                   7739: 
1.157     albertel 7740: </script>
                   7741: 
1.566     raeburn  7742: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7743: 
1.492     albertel 7744: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7745: '.$default_form_data.
                   7746:   &Apache::lonhtmlcommon::start_pick_box().
                   7747:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7748:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7749:   &Apache::lonhtmlcommon::row_closure().
                   7750:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7751:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7752:   &Apache::lonhtmlcommon::row_closure().
                   7753:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7754:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7755:   &Apache::lonhtmlcommon::row_closure().
                   7756:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7757:   '<input type="file" name="upfile" size="50" />'.
                   7758:   &Apache::lonhtmlcommon::row_closure(1).
                   7759:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7760: 
1.492     albertel 7761: <input name="command" value="scantronupload_save" type="hidden" />
1.575   ! www      7762: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7763: </form>
1.492     albertel 7764: ');
1.157     albertel 7765:     return '';
                   7766: }
                   7767: 
1.423     albertel 7768: 
1.157     albertel 7769: sub scantron_upload_scantron_data_save {
                   7770:     my($r)=@_;
1.324     albertel 7771:     my ($symb)=&get_symb($r,1);
1.182     albertel 7772:     my $doanotherupload=
                   7773: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7774: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7775: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7776: 	'</form>'."\n";
1.257     albertel 7777:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7778: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7779: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575   ! www      7780: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 7781: 	if ($symb) {
1.324     albertel 7782: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7783: 	} else {
                   7784: 	    $r->print($doanotherupload);
                   7785: 	}
1.162     albertel 7786: 	return '';
                   7787:     }
1.257     albertel 7788:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7789:     my $uploadedfile;
1.567     raeburn  7790:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7791:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7792:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7793:     } else {
1.568     raeburn  7794:         my $result = 
                   7795:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7796:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7797: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7798: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7799:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7800: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7801:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7802:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7803:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7804: 	} else {
1.567     raeburn  7805: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7806:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7807: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7808: 	}
                   7809:     }
1.174     albertel 7810:     if ($symb) {
1.209     ng       7811: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7812:     } else {
1.182     albertel 7813: 	$r->print($doanotherupload);
1.174     albertel 7814:     }
1.157     albertel 7815:     return '';
                   7816: }
                   7817: 
1.567     raeburn  7818: sub validate_uploaded_scantron_file {
                   7819:     my ($cdom,$cname,$fname) = @_;
                   7820:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7821:     my @lines;
                   7822:     if ($scanlines ne '-1') {
                   7823:         @lines=split("\n",$scanlines,-1);
                   7824:     }
                   7825:     my $output;
                   7826:     if (@lines) {
                   7827:         my (%counts,$max_match_format);
                   7828:         my ($max_match_count,$max_match_pct) = (0,0);
                   7829:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7830:         my %idmap = &username_to_idmap($classlist);
                   7831:         foreach my $key (keys(%idmap)) {
                   7832:             my $lckey = lc($key);
                   7833:             $idmap{$lckey} = $idmap{$key};
                   7834:         }
                   7835:         my %unique_formats;
                   7836:         my @formatlines = &get_scantronformat_file();
                   7837:         foreach my $line (@formatlines) {
                   7838:             chomp($line);
                   7839:             my @config = split(/:/,$line);
                   7840:             my $idstart = $config[5];
                   7841:             my $idlength = $config[6];
                   7842:             if (($idstart ne '') && ($idlength > 0)) {
                   7843:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7844:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7845:                 } else {
                   7846:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7847:                 }
                   7848:             }
                   7849:         }
                   7850:         foreach my $key (keys(%unique_formats)) {
                   7851:             my ($idstart,$idlength) = split(':',$key);
                   7852:             %{$counts{$key}} = (
                   7853:                                'found'   => 0,
                   7854:                                'total'   => 0,
                   7855:                               );
                   7856:             foreach my $line (@lines) {
                   7857:                 next if ($line =~ /^#/);
                   7858:                 next if ($line =~ /^[\s\cz]*$/);
                   7859:                 my $id = substr($line,$idstart-1,$idlength);
                   7860:                 $id = lc($id);
                   7861:                 if (exists($idmap{$id})) {
                   7862:                     $counts{$key}{'found'} ++;
                   7863:                 }
                   7864:                 $counts{$key}{'total'} ++;
                   7865:             }
                   7866:             if ($counts{$key}{'total'}) {
                   7867:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7868:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7869:                     $max_match_pct = $percent_match;
                   7870:                     $max_match_format = $key;
                   7871:                     $max_match_count = $counts{$key}{'total'};
                   7872:                 }
                   7873:             }
                   7874:         }
                   7875:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   7876:             my $format_descs;
                   7877:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   7878:             for (my $i=0; $i<$numwithformat; $i++) {
                   7879:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   7880:                 if ($i<$numwithformat-2) {
                   7881:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   7882:                 } elsif ($i==$numwithformat-2) {
                   7883:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   7884:                 } elsif ($i==$numwithformat-1) {
                   7885:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   7886:                 }
                   7887:             }
                   7888:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   7889:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   7890:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   7891:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   7892:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   7893:                                   '<i>'.$cdom.'</i>').'</li>'.
                   7894:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   7895:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   7896:                        '</ul>';
                   7897:         }
                   7898:     } else {
                   7899:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   7900:     }
                   7901:     return $output;
                   7902: }
                   7903: 
1.202     albertel 7904: sub valid_file {
                   7905:     my ($requested_file)=@_;
                   7906:     foreach my $filename (sort(&scantron_filenames())) {
                   7907: 	if ($requested_file eq $filename) { return 1; }
                   7908:     }
                   7909:     return 0;
                   7910: }
                   7911: 
                   7912: sub scantron_download_scantron_data {
                   7913:     my ($r)=@_;
1.324     albertel 7914:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7915:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7916:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7917:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7918:     if (! &valid_file($file)) {
1.492     albertel 7919: 	$r->print('
1.202     albertel 7920: 	<p>
1.492     albertel 7921: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7922:         </p>
1.492     albertel 7923: ');
1.324     albertel 7924: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7925: 	return;
                   7926:     }
                   7927:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7928:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7929:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7930:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7931:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7932:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7933:     $r->print('
1.202     albertel 7934:     <p>
1.492     albertel 7935: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7936: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7937:     </p>
                   7938:     <p>
1.492     albertel 7939: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7940: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7941:     </p>
                   7942:     <p>
1.492     albertel 7943: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7944: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7945:     </p>
1.492     albertel 7946: ');
1.324     albertel 7947:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7948:     return '';
                   7949: }
1.157     albertel 7950: 
1.523     raeburn  7951: sub checkscantron_results {
                   7952:     my ($r) = @_;
                   7953:     my ($symb)=&get_symb($r);
                   7954:     if (!$symb) {return '';}
                   7955:     my $grading_menu_button=&show_grading_menu_form($symb);
                   7956:     my $cid = $env{'request.course.id'};
1.542     raeburn  7957:     my %lettdig = &letter_to_digits();
1.523     raeburn  7958:     my $numletts = scalar(keys(%lettdig));
                   7959:     my $cnum = $env{'course.'.$cid.'.num'};
                   7960:     my $cdom = $env{'course.'.$cid.'.domain'};
                   7961:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7962:     my %record;
                   7963:     my %scantron_config =
                   7964:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   7965:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   7966:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7967:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   7968:     my $navmap=Apache::lonnavmaps::navmap->new();
                   7969:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  7970:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7971:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7972:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   7973: 
1.554     raeburn  7974:     my ($uname,$udom);
1.523     raeburn  7975:     my (%scandata,%lastname,%bylast);
                   7976:     $r->print('
                   7977: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   7978: 
                   7979:     my @delayqueue;
                   7980:     my %completedstudents;
                   7981: 
                   7982:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
                   7983:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
                   7984:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
                   7985:                                     'inline',undef,'checkscantron');
1.546     raeburn  7986:     my ($username,$domain,$started);
1.523     raeburn  7987: 
1.557     raeburn  7988:     &scantron_get_maxbubble();  # Need the bubble lines array to parse.
1.523     raeburn  7989: 
                   7990:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7991:                                           'Processing first student');
                   7992:     my $start=&Time::HiRes::time();
                   7993:     my $i=-1;
                   7994: 
                   7995:     while ($i<$scanlines->{'count'}) {
                   7996:         ($username,$domain,$uname)=('','','');
                   7997:         $i++;
                   7998:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   7999:         if ($line=~/^[\s\cz]*$/) { next; }
                   8000:         if ($started) {
                   8001:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8002:                                                      'last student');
                   8003:         }
                   8004:         $started=1;
                   8005:         my $scan_record=
                   8006:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8007:                                                      $scan_data);
                   8008:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8009:                                                               \%idmap,$i)) {
                   8010:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8011:                                 'Unable to find a student that matches',1);
                   8012:             next;
                   8013:         }
                   8014:         if (exists $completedstudents{$uname}) {
                   8015:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8016:                                 'Student '.$uname.' has multiple sheets',2);
                   8017:             next;
                   8018:         }
                   8019:         my $pid = $scan_record->{'scantron.ID'};
                   8020:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8021:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8022:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8023:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8024:         chomp($scandata{$pid});
                   8025:         $scandata{$pid} =~ s/\r$//;
                   8026:         ($username,$domain)=split(/:/,$uname);
                   8027:         my $counter = -1;
                   8028:         foreach my $resource (@resources) {
1.557     raeburn  8029:             my $parts;
1.554     raeburn  8030:             my $ressymb = $resource->symb();
1.557     raeburn  8031:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8032:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8033:                 (my $analysis,$parts) =
                   8034:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8035:             } else {
                   8036:                 $parts = $grader_partids_by_symb{$ressymb};
                   8037:             }
1.542     raeburn  8038:             ($counter,my $recording) =
                   8039:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8040:                                          $scandata{$pid},$parts,
1.542     raeburn  8041:                                          \%scantron_config,\%lettdig,$numletts);
                   8042:             $record{$pid} .= $recording;
1.523     raeburn  8043:         }
                   8044:     }
                   8045:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8046:     $r->print('<br />');
                   8047:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8048:     $passed = 0;
                   8049:     $failed = 0;
                   8050:     $numstudents = 0;
                   8051:     foreach my $last (sort(keys(%bylast))) {
                   8052:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8053:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8054:                 my $showscandata = $scandata{$pid};
                   8055:                 my $showrecord = $record{$pid};
                   8056:                 $showscandata =~ s/\s/&nbsp;/g;
                   8057:                 $showrecord =~ s/\s/&nbsp;/g;
                   8058:                 if ($scandata{$pid} eq $record{$pid}) {
                   8059:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8060:                     $okstudents .= '<tr class="'.$css_class.'">'.
                   8061: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8062: '</tr>'."\n".
                   8063: '<tr class="'.$css_class.'">'."\n".
                   8064: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8065:                     $passed ++;
                   8066:                 } else {
                   8067:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
                   8068:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8069: '</tr>'."\n".
                   8070: '<tr class="'.$css_class.'">'."\n".
                   8071: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8072: '</tr>'."\n";
                   8073:                     $failed ++;
                   8074:                 }
                   8075:                 $numstudents ++;
                   8076:             }
                   8077:         }
                   8078:     }
1.572     www      8079:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
1.523     raeburn  8080:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
                   8081:     if ($passed) {
1.572     www      8082:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8083:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8084:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8085:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8086:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8087:                  $okstudents."\n".
                   8088:                  &Apache::loncommon::end_data_table().'<br />');
                   8089:     }
                   8090:     if ($failed) {
1.572     www      8091:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8092:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8093:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8094:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8095:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8096:                  $badstudents."\n".
                   8097:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8098:                  &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  8099:     }
                   8100:     $r->print('</form><br />'.$grading_menu_button);
                   8101:     return;
                   8102: }
                   8103: 
1.542     raeburn  8104: sub verify_scantron_grading {
1.554     raeburn  8105:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8106:         $scantron_config,$lettdig,$numletts) = @_;
                   8107:     my ($record,%expected,%startpos);
                   8108:     return ($counter,$record) if (!ref($resource));
                   8109:     return ($counter,$record) if (!$resource->is_problem());
                   8110:     my $symb = $resource->symb();
1.554     raeburn  8111:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8112:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8113:         $counter ++;
                   8114:         $expected{$part_id} = 0;
                   8115:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8116:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8117:             foreach my $item (@sub_lines) {
                   8118:                 $expected{$part_id} += $item;
                   8119:             }
                   8120:         } else {
                   8121:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8122:         }
                   8123:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8124:     }
                   8125:     if ($symb) {
                   8126:         my %recorded;
                   8127:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8128:         if ($returnhash{'version'}) {
                   8129:             my %lasthash=();
                   8130:             my $version;
                   8131:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8132:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8133:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8134:                 }
                   8135:             }
                   8136:             foreach my $key (keys(%lasthash)) {
                   8137:                 if ($key =~ /\.scantron$/) {
                   8138:                     my $value = &unescape($lasthash{$key});
                   8139:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8140:                     if ($value eq '') {
                   8141:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8142:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8143:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8144:                             }
                   8145:                         }
                   8146:                     } else {
                   8147:                         my @tocheck;
                   8148:                         my @items = split(//,$value);
                   8149:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8150:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8151:                             if (@items < $expected{$part_id}) {
                   8152:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8153:                                 my @singles = split(//,$fragment);
                   8154:                                 foreach my $pos (@singles) {
                   8155:                                     if ($pos eq ' ') {
                   8156:                                         push(@tocheck,$pos);
                   8157:                                     } else {
                   8158:                                         my $next = shift(@items);
                   8159:                                         push(@tocheck,$next);
                   8160:                                     }
                   8161:                                 }
                   8162:                             } else {
                   8163:                                 @tocheck = @items;
                   8164:                             }
                   8165:                             foreach my $letter (@tocheck) {
                   8166:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8167:                                     if ($letter !~ /^[A-J]$/) {
                   8168:                                         $letter = $scantron_config->{'Qoff'};
                   8169:                                     }
                   8170:                                     $recorded{$part_id} .= $letter;
                   8171:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8172:                                     my $digit;
                   8173:                                     if ($letter !~ /^[A-J]$/) {
                   8174:                                         $digit = $scantron_config->{'Qoff'};
                   8175:                                     } else {
                   8176:                                         $digit = $lettdig->{$letter};
                   8177:                                     }
                   8178:                                     $recorded{$part_id} .= $digit;
                   8179:                                 }
                   8180:                             }
                   8181:                         } else {
                   8182:                             @tocheck = @items;
                   8183:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8184:                                 my $curr_sub = shift(@tocheck);
                   8185:                                 my $digit;
                   8186:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8187:                                     $digit = $lettdig->{$curr_sub}-1;
                   8188:                                 }
                   8189:                                 if ($curr_sub eq 'J') {
                   8190:                                     $digit += scalar($numletts);
                   8191:                                 }
                   8192:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8193:                                     if ($j == $digit) {
                   8194:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8195:                                     } else {
                   8196:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8197:                                     }
                   8198:                                 }
                   8199:                             }
                   8200:                         }
                   8201:                     }
                   8202:                 }
                   8203:             }
                   8204:         }
1.554     raeburn  8205:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8206:             if ($recorded{$part_id} eq '') {
                   8207:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8208:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8209:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8210:                     }
                   8211:                 }
                   8212:             }
                   8213:             $record .= $recorded{$part_id};
                   8214:         }
                   8215:     }
                   8216:     return ($counter,$record);
                   8217: }
                   8218: 
                   8219: sub letter_to_digits { 
                   8220:     my %lettdig = (
                   8221:                     A => 1,
                   8222:                     B => 2,
                   8223:                     C => 3,
                   8224:                     D => 4,
                   8225:                     E => 5,
                   8226:                     F => 6,
                   8227:                     G => 7,
                   8228:                     H => 8,
                   8229:                     I => 9,
                   8230:                     J => 0,
                   8231:                   );
                   8232:     return %lettdig;
                   8233: }
                   8234: 
1.423     albertel 8235: 
1.75      albertel 8236: #-------- end of section for handling grading scantron forms -------
                   8237: #
                   8238: #-------------------------------------------------------------------
                   8239: 
1.72      ng       8240: #-------------------------- Menu interface -------------------------
                   8241: #
                   8242: #--- Show a Grading Menu button - Calls the next routine ---
                   8243: sub show_grading_menu_form {
1.324     albertel 8244:     my ($symb)=@_;
1.125     ng       8245:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8246: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8247: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8248: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8249: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8250: 	'</form>'."\n";
                   8251:     return $result;
                   8252: }
                   8253: 
1.77      ng       8254: # -- Retrieve choices for grading form
                   8255: sub savedState {
                   8256:     my %savedState = ();
1.257     albertel 8257:     if ($env{'form.saveState'}) {
                   8258: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8259: 	    my ($key,$value) = split(/=/,$_,2);
                   8260: 	    $savedState{$key} = $value;
                   8261: 	}
                   8262:     }
                   8263:     return \%savedState;
                   8264: }
1.76      ng       8265: 
1.443     banghart 8266: sub grading_menu {
                   8267:     my ($request) = @_;
                   8268:     my ($symb)=&get_symb($request);
                   8269:     if (!$symb) {return '';}
                   8270:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8271:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8272: 
1.444     banghart 8273:     $request->print($table);
1.443     banghart 8274:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8275:                   'handgrade'=>$hdgrade,
                   8276:                   'probTitle'=>$probTitle,
                   8277:                   'command'=>'submit_options',
                   8278:                   'saveState'=>"",
                   8279:                   'gradingMenu'=>1,
                   8280:                   'showgrading'=>"yes");
1.538     schulted 8281:     
                   8282:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8283:     
1.443     banghart 8284:     $fields{'command'} = 'csvform';
1.538     schulted 8285:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8286:     
1.443     banghart 8287:     $fields{'command'} = 'processclicker';
1.538     schulted 8288:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8289:     
1.443     banghart 8290:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8291:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8292:     
                   8293:     my @menu = ({	categorytitle=>'Course Grading',
                   8294:             items =>[
                   8295:                         {	linktext => 'Manual Grading/View Submissions',
                   8296:                     		url => $url1,
                   8297:                     		permission => 'F',
                   8298:                     		icon => 'edit-find-replace.png',
                   8299:                     		linktitle => 'Start the process of hand grading submissions.'
                   8300:                         },
                   8301:                 	    {	linktext => 'Upload Scores',
                   8302:                     		url => $url2,
                   8303:                     		permission => 'F',
                   8304:                     		icon => 'uploadscores.png',
                   8305:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8306:                 	    },
                   8307:                 	    {	linktext => 'Process Clicker',
                   8308:                     		url => $url3,
                   8309:                     		permission => 'F',
                   8310:                     		icon => 'addClickerInfoFile.png',
                   8311:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8312:                 	    },
                   8313:                 	    {	linktext => 'Grade/Manage/Review Scantron Forms',
                   8314:                     		url => $url4,
                   8315:                     		permission => 'F',
                   8316:                     		icon => 'stat.png',
                   8317:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
                   8318:                 	    }
                   8319:                     ]
                   8320:             });
                   8321: 
                   8322:     #$fields{'command'} = 'verify';
                   8323:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 8324:     #
                   8325:     # Create the menu
                   8326:     my $Str;
1.444     banghart 8327:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8328:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8329:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8330:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8331: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8332: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8333: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8334: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8335: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8336: 
1.538     schulted 8337:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   8338:     #$menudata->{'jscript'}
                   8339:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
                   8340:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   8341:         ' /> '.
                   8342:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                   8343:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
                   8344: 
1.444     banghart 8345:     $Str .="</form>\n";
1.539     riegler  8346:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 8347:     $request->print(<<GRADINGMENUJS);
                   8348: <script type="text/javascript" language="javascript">
                   8349:     function checkChoice(formname,val,cmdx) {
                   8350: 	if (val <= 2) {
                   8351: 	    var cmd = radioSelection(formname.radioChoice);
                   8352: 	    var cmdsave = cmd;
                   8353: 	} else {
                   8354: 	    cmd = cmdx;
                   8355: 	    cmdsave = 'submission';
                   8356: 	}
                   8357: 	formname.command.value = cmd;
                   8358: 	if (val < 5) formname.submit();
                   8359: 	if (val == 5) {
1.458     banghart 8360: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8361: 	        return false;
                   8362: 	    } else {
                   8363: 	        formname.submit();
                   8364: 	    }
1.445     banghart 8365: 	}
                   8366:     }
1.443     banghart 8367: 
                   8368:     function checkReceiptNo(formname,nospace) {
                   8369: 	var receiptNo = formname.receipt.value;
                   8370: 	var checkOpt = false;
                   8371: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8372: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8373: 	if (checkOpt) {
1.539     riegler  8374: 	    alert("$receiptalert");
1.443     banghart 8375: 	    formname.receipt.value = "";
                   8376: 	    formname.receipt.focus();
                   8377: 	    return false;
                   8378: 	}
                   8379: 	return true;
                   8380:     }
                   8381: </script>
                   8382: GRADINGMENUJS
                   8383:     &commonJSfunctions($request);
                   8384:     return $Str;    
                   8385: }
                   8386: 
                   8387: 
                   8388: #--- Displays the submissions first page -------
                   8389: sub submit_options {
1.72      ng       8390:     my ($request) = @_;
1.324     albertel 8391:     my ($symb)=&get_symb($request);
1.72      ng       8392:     if (!$symb) {return '';}
1.76      ng       8393:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8394: 
1.539     riegler  8395:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       8396:     $request->print(<<GRADINGMENUJS);
                   8397: <script type="text/javascript" language="javascript">
1.116     ng       8398:     function checkChoice(formname,val,cmdx) {
                   8399: 	if (val <= 2) {
                   8400: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8401: 	    var cmdsave = cmd;
1.116     ng       8402: 	} else {
                   8403: 	    cmd = cmdx;
1.118     ng       8404: 	    cmdsave = 'submission';
1.116     ng       8405: 	}
                   8406: 	formname.command.value = cmd;
1.118     ng       8407: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8408: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8409: 	if (val < 5) formname.submit();
                   8410: 	if (val == 5) {
1.72      ng       8411: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8412: 	    formname.submit();
                   8413: 	}
1.238     albertel 8414: 	if (val < 7) formname.submit();
1.72      ng       8415:     }
                   8416: 
                   8417:     function checkReceiptNo(formname,nospace) {
                   8418: 	var receiptNo = formname.receipt.value;
                   8419: 	var checkOpt = false;
                   8420: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8421: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8422: 	if (checkOpt) {
1.539     riegler  8423: 	    alert("$receiptalert");
1.72      ng       8424: 	    formname.receipt.value = "";
                   8425: 	    formname.receipt.focus();
                   8426: 	    return false;
                   8427: 	}
                   8428: 	return true;
                   8429:     }
                   8430: </script>
                   8431: GRADINGMENUJS
1.118     ng       8432:     &commonJSfunctions($request);
1.324     albertel 8433:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8434:     my $result;
1.76      ng       8435:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8436:     my $savedState = &savedState();
1.118     ng       8437:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8438:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8439:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8440:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8441: 
1.533     bisitz   8442:     # Preselect sections
                   8443:     my $selsec="";
                   8444:     if (ref($sections)) {
                   8445:         foreach my $section (sort(@$sections)) {
                   8446:             $selsec.='<option value="'.$section.'" '.
                   8447:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8448:         }
                   8449:     }
                   8450: 
1.72      ng       8451:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8452: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8453: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8454: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8455: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8456: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8457: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8458: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8459: 
1.472     albertel 8460:     $result.='
1.533     bisitz   8461: <h2>
                   8462:   '.&mt('Grade Current Resource').'
                   8463: </h2>
                   8464: <div>
                   8465:   '.$table.'
                   8466: </div>
                   8467: 
1.537     harmsja  8468: <div class="LC_columnSection">
                   8469:   
1.533     bisitz   8470:     <fieldset>
                   8471:       <legend>
                   8472:        '.&mt('Sections').'
                   8473:       </legend>
                   8474:       <select name="section" multiple="multiple" size="5">'."\n";
                   8475:     $result.= $selsec;
1.401     albertel 8476:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8477:     $result.='
1.533     bisitz   8478:     </fieldset>
1.537     harmsja  8479:   
1.533     bisitz   8480:     <fieldset>
                   8481:       <legend>
                   8482:         '.&mt('Groups').'
                   8483:       </legend>
                   8484:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8485:     </fieldset>
1.537     harmsja  8486:   
1.533     bisitz   8487:     <fieldset>
                   8488:       <legend>
                   8489:         '.&mt('Access Status').'
                   8490:       </legend>
                   8491:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8492:     </fieldset>
1.537     harmsja  8493:   
1.533     bisitz   8494:     <fieldset>
                   8495:       <legend>
                   8496:         '.&mt('Submission Status').'
                   8497:       </legend>
                   8498:       <select name="submitonly" size="5">
1.473     albertel 8499: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8500: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8501: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8502: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8503:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   8504:       </select>
                   8505:     </fieldset>
1.537     harmsja  8506:   
1.533     bisitz   8507: </div>
                   8508: 
                   8509: <br />
                   8510:           <div>
                   8511:             <div>
1.473     albertel 8512:               <label>
                   8513:                 <input type="radio" name="radioChoice" value="submission" '.
                   8514:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8515:              &mt('Select individual students to grade and view submissions.').'
                   8516: 	      </label> 
                   8517:             </div>
1.533     bisitz   8518:             <div>
1.473     albertel 8519: 	      <label>
                   8520:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8521:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8522:                     &mt('Grade all selected students in a grading table.').'
                   8523:               </label>
                   8524:             </div>
1.533     bisitz   8525:             <div>
1.539     riegler  8526: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8527:             </div>
1.472     albertel 8528:           </div>
1.533     bisitz   8529: 
                   8530: 
1.473     albertel 8531:         <h2>
                   8532:          '.&mt('Grade Complete Folder for One Student').'
                   8533:         </h2>
1.533     bisitz   8534:         <div>
                   8535:             <div>
1.473     albertel 8536:               <label>
                   8537:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8538: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8539:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8540:               </label>
                   8541:             </div>
1.533     bisitz   8542:             <div>
1.539     riegler  8543: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8544:             </div>
1.472     albertel 8545:         </div>
                   8546:   </form>';
1.499     albertel 8547:     $result .= &show_grading_menu_form($symb);
1.44      ng       8548:     return $result;
1.2       albertel 8549: }
                   8550: 
1.285     albertel 8551: sub reset_perm {
                   8552:     undef(%perm);
                   8553: }
                   8554: 
                   8555: sub init_perm {
                   8556:     &reset_perm();
1.300     albertel 8557:     foreach my $test_perm ('vgr','mgr','opa') {
                   8558: 
                   8559: 	my $scope = $env{'request.course.id'};
                   8560: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8561: 
                   8562: 	    $scope .= '/'.$env{'request.course.sec'};
                   8563: 	    if ( $perm{$test_perm}=
                   8564: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8565: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8566: 	    } else {
                   8567: 		delete($perm{$test_perm});
                   8568: 	    }
1.285     albertel 8569: 	}
                   8570:     }
                   8571: }
                   8572: 
1.400     www      8573: sub gather_clicker_ids {
1.408     albertel 8574:     my %clicker_ids;
1.400     www      8575: 
                   8576:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8577: 
                   8578:     # Set up a couple variables.
1.407     albertel 8579:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8580:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8581:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8582: 
1.407     albertel 8583:     foreach my $student (keys(%$classlist)) {
1.438     www      8584:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8585:         my $username = $classlist->{$student}->[$username_idx];
                   8586:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8587:         my $clickers =
1.408     albertel 8588: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8589:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8590:             $id=~s/^[\#0]+//;
1.421     www      8591:             $id=~s/[\-\:]//g;
1.407     albertel 8592:             if (exists($clicker_ids{$id})) {
1.408     albertel 8593: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8594:             } else {
1.408     albertel 8595: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8596:             }
                   8597:         }
                   8598:     }
1.407     albertel 8599:     return %clicker_ids;
1.400     www      8600: }
                   8601: 
1.402     www      8602: sub gather_adv_clicker_ids {
1.408     albertel 8603:     my %clicker_ids;
1.402     www      8604:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8605:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8606:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8607:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8608:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8609:             my ($puname,$pudom)=split(/\:/,$person);
                   8610:             my $clickers =
1.408     albertel 8611: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8612:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8613: 		$id=~s/^[\#0]+//;
1.421     www      8614:                 $id=~s/[\-\:]//g;
1.408     albertel 8615: 		if (exists($clicker_ids{$id})) {
                   8616: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8617: 		} else {
                   8618: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8619: 		}
1.405     www      8620:             }
1.402     www      8621:         }
                   8622:     }
1.407     albertel 8623:     return %clicker_ids;
1.402     www      8624: }
                   8625: 
1.413     www      8626: sub clicker_grading_parameters {
                   8627:     return ('gradingmechanism' => 'scalar',
                   8628:             'upfiletype' => 'scalar',
                   8629:             'specificid' => 'scalar',
                   8630:             'pcorrect' => 'scalar',
                   8631:             'pincorrect' => 'scalar');
                   8632: }
                   8633: 
1.400     www      8634: sub process_clicker {
                   8635:     my ($r)=@_;
                   8636:     my ($symb)=&get_symb($r);
                   8637:     if (!$symb) {return '';}
                   8638:     my $result=&checkforfile_js();
                   8639:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8640:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8641:     $result.=$table;
                   8642:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8643:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8644:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8645:         '</b></td></tr>'."\n";
1.400     www      8646:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8647: # Attempt to restore parameters from last session, set defaults if not present
                   8648:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8649:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8650:                                                  \%Saveable_Parameters);
                   8651:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8652:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8653:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8654:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8655: 
                   8656:     my %checked;
1.521     www      8657:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8658:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8659:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8660:        }
                   8661:     }
                   8662: 
1.400     www      8663:     my $upload=&mt("Upload File");
                   8664:     my $type=&mt("Type");
1.402     www      8665:     my $attendance=&mt("Award points just for participation");
                   8666:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8667:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8668:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8669:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8670:     my $pcorrect=&mt("Percentage points for correct solution");
                   8671:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8672:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8673: 						   ('iclicker' => 'i>clicker',
                   8674:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8675:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8676:     $result.=<<ENDUPFORM;
1.402     www      8677: <script type="text/javascript">
                   8678: function sanitycheck() {
                   8679: // Accept only integer percentages
                   8680:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8681:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8682: // Find out grading choice
                   8683:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8684:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8685:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8686:       }
                   8687:    }
                   8688: // By default, new choice equals user selection
                   8689:    newgradingchoice=gradingchoice;
                   8690: // Not good to give more points for false answers than correct ones
                   8691:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8692:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8693:    }
                   8694: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8695:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8696:       document.forms.gradesupload.pcorrect.value=100;
                   8697:       document.forms.gradesupload.pincorrect.value=100;
                   8698:    }
                   8699: // If the values are different, cannot be attendance only
                   8700:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8701:        (gradingchoice=='attendance')) {
                   8702:        newgradingchoice='personnel';
                   8703:    }
                   8704: // Change grading choice to new one
                   8705:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8706:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8707:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8708:       } else {
                   8709:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8710:       }
                   8711:    }
                   8712: // Remember the old state
                   8713:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8714: }
                   8715: </script>
1.400     www      8716: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8717: <input type="hidden" name="symb" value="$symb" />
                   8718: <input type="hidden" name="command" value="processclickerfile" />
                   8719: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8720: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8721: <input type="file" name="upfile" size="50" />
                   8722: <br /><label>$type: $selectform</label>
1.569     bisitz   8723: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8724: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8725: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8726: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.569     bisitz   8727: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
1.521     www      8728: <br />&nbsp;&nbsp;&nbsp;
                   8729: <input type="text" name="givenanswer" size="50" />
1.413     www      8730: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8731: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8732: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8733: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8734: </form>
                   8735: ENDUPFORM
                   8736:     $result.='</td></tr></table>'."\n".
                   8737:              '</td></tr></table><br /><br />'."\n";
                   8738:     $result.=&show_grading_menu_form($symb);
                   8739:     return $result;
                   8740: }
                   8741: 
                   8742: sub process_clicker_file {
                   8743:     my ($r)=@_;
                   8744:     my ($symb)=&get_symb($r);
                   8745:     if (!$symb) {return '';}
1.413     www      8746: 
                   8747:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8748:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8749:                                               \%Saveable_Parameters);
                   8750: 
1.400     www      8751:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8752:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8753: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8754: 	return $result.&show_grading_menu_form($symb);
1.404     www      8755:     }
1.522     www      8756:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8757:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8758:         return $result.&show_grading_menu_form($symb);
                   8759:     }
1.522     www      8760:     my $foundgiven=0;
1.521     www      8761:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8762:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8763:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8764:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8765:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8766:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8767:         $foundgiven=$#answers+1;
1.521     www      8768:     }
1.407     albertel 8769:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8770:     my %correct_ids;
1.404     www      8771:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8772: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8773:     }
                   8774:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8775: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8776: 	   $correct_id=~tr/a-z/A-Z/;
                   8777: 	   $correct_id=~s/\s//gs;
                   8778: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8779:            $correct_id=~s/[\-\:]//g;
1.414     www      8780:            if ($correct_id) {
                   8781: 	      $correct_ids{$correct_id}='specified';
                   8782:            }
                   8783:         }
1.400     www      8784:     }
1.404     www      8785:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8786: 	$result.=&mt('Score based on attendance only');
1.521     www      8787:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8788:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8789:     } else {
1.408     albertel 8790: 	my $number=0;
1.411     www      8791: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8792: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8793: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8794: 	    if ($correct_ids{$id} eq 'specified') {
                   8795: 		$result.=&mt('specified');
                   8796: 	    } else {
                   8797: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8798: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8799: 	    }
                   8800: 	    $number++;
                   8801: 	}
1.411     www      8802:         $result.="</p>\n";
1.408     albertel 8803: 	if ($number==0) {
                   8804: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8805: 	    return $result.&show_grading_menu_form($symb);
                   8806: 	}
1.404     www      8807:     }
1.405     www      8808:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8809:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8810: 		     '<span class="LC_error">',
                   8811: 		     '</span>',
                   8812: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8813:         return $result.&show_grading_menu_form($symb);
                   8814:     }
1.410     www      8815: 
                   8816: # Were able to get all the info needed, now analyze the file
                   8817: 
1.411     www      8818:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8819:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8820:     my $heading=&mt('Scanning clicker file');
                   8821:     $result.=(<<ENDHEADER);
                   8822: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8823: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8824: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8825: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8826: <input type="hidden" name="symb" value="$symb" />
                   8827: <input type="hidden" name="command" value="assignclickergrades" />
                   8828: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8829: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8830: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8831: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8832: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8833: ENDHEADER
1.522     www      8834:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8835:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8836:     } 
1.408     albertel 8837:     my %responses;
                   8838:     my @questiontitles;
1.405     www      8839:     my $errormsg='';
                   8840:     my $number=0;
                   8841:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8842: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8843:     }
1.419     www      8844:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8845:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8846:     }
1.411     www      8847:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8848:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8849:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8850:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8851:              '<br />';
1.522     www      8852:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8853:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8854:        return $result.&show_grading_menu_form($symb);
                   8855:     } 
1.414     www      8856: # Remember Question Titles
                   8857: # FIXME: Possibly need delimiter other than ":"
                   8858:     for (my $i=0;$i<$number;$i++) {
                   8859:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8860:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8861:     }
1.411     www      8862:     my $correct_count=0;
                   8863:     my $student_count=0;
                   8864:     my $unknown_count=0;
1.414     www      8865: # Match answers with usernames
                   8866: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8867:     foreach my $id (keys(%responses)) {
1.410     www      8868:        if ($correct_ids{$id}) {
1.414     www      8869:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8870:           $correct_count++;
1.410     www      8871:        } elsif ($clicker_ids{$id}) {
1.437     www      8872:           if ($clicker_ids{$id}=~/\,/) {
                   8873: # More than one user with the same clicker!
                   8874:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8875:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8876:                            "<select name='multi".$id."'>";
                   8877:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8878:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8879:              }
                   8880:              $result.='</select>';
                   8881:              $unknown_count++;
                   8882:           } else {
                   8883: # Good: found one and only one user with the right clicker
                   8884:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8885:              $student_count++;
                   8886:           }
1.410     www      8887:        } else {
1.411     www      8888:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8889:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8890:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8891:                    "\n".&mt("Domain").": ".
                   8892:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8893:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8894:           $unknown_count++;
1.410     www      8895:        }
1.405     www      8896:     }
1.412     www      8897:     $result.='<hr />'.
                   8898:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8899:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8900:        if ($correct_count==0) {
                   8901:           $errormsg.="Found no correct answers answers for grading!";
                   8902:        } elsif ($correct_count>1) {
1.414     www      8903:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8904:        }
                   8905:     }
1.428     www      8906:     if ($number<1) {
                   8907:        $errormsg.="Found no questions.";
                   8908:     }
1.412     www      8909:     if ($errormsg) {
                   8910:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8911:     } else {
                   8912:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8913:     }
                   8914:     $result.='</form></td></tr></table>'."\n".
1.410     www      8915:              '</td></tr></table><br /><br />'."\n";
1.404     www      8916:     return $result.&show_grading_menu_form($symb);
1.400     www      8917: }
                   8918: 
1.405     www      8919: sub iclicker_eval {
1.406     www      8920:     my ($questiontitles,$responses)=@_;
1.405     www      8921:     my $number=0;
                   8922:     my $errormsg='';
                   8923:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8924:         my %components=&Apache::loncommon::record_sep($line);
                   8925:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8926: 	if ($entries[0] eq 'Question') {
                   8927: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8928: 		$$questiontitles[$number]=$entries[$i];
                   8929: 		$number++;
                   8930: 	    }
                   8931: 	}
                   8932: 	if ($entries[0]=~/^\#/) {
                   8933: 	    my $id=$entries[0];
                   8934: 	    my @idresponses;
                   8935: 	    $id=~s/^[\#0]+//;
                   8936: 	    for (my $i=0;$i<$number;$i++) {
                   8937: 		my $idx=3+$i*6;
                   8938: 		push(@idresponses,$entries[$idx]);
                   8939: 	    }
                   8940: 	    $$responses{$id}=join(',',@idresponses);
                   8941: 	}
1.405     www      8942:     }
                   8943:     return ($errormsg,$number);
                   8944: }
                   8945: 
1.419     www      8946: sub interwrite_eval {
                   8947:     my ($questiontitles,$responses)=@_;
                   8948:     my $number=0;
                   8949:     my $errormsg='';
1.420     www      8950:     my $skipline=1;
                   8951:     my $questionnumber=0;
                   8952:     my %idresponses=();
1.419     www      8953:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8954:         my %components=&Apache::loncommon::record_sep($line);
                   8955:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8956:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8957:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8958:         next if $skipline;
                   8959:         if ($entries[0]!=$questionnumber) {
                   8960:            $questionnumber=$entries[0];
                   8961:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8962:            $number++;
1.419     www      8963:         }
1.420     www      8964:         my $id=$entries[4];
                   8965:         $id=~s/^[\#0]+//;
1.421     www      8966:         $id=~s/^v\d*\://i;
                   8967:         $id=~s/[\-\:]//g;
1.420     www      8968:         $idresponses{$id}[$number]=$entries[6];
                   8969:     }
1.524     raeburn  8970:     foreach my $id (keys(%idresponses)) {
1.420     www      8971:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8972:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8973:     }
                   8974:     return ($errormsg,$number);
                   8975: }
                   8976: 
1.414     www      8977: sub assign_clicker_grades {
                   8978:     my ($r)=@_;
                   8979:     my ($symb)=&get_symb($r);
                   8980:     if (!$symb) {return '';}
1.416     www      8981: # See which part we are saving to
                   8982:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8983: # FIXME: This should probably look for the first handgradeable part
                   8984:     my $part=$$partlist[0];
                   8985: # Start screen output
1.414     www      8986:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8987: 
1.414     www      8988:     my $heading=&mt('Assigning grades based on clicker file');
                   8989:     $result.=(<<ENDHEADER);
                   8990: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8991: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8992: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8993: ENDHEADER
                   8994: # Get correct result
                   8995: # FIXME: Possibly need delimiter other than ":"
                   8996:     my @correct=();
1.415     www      8997:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8998:     my $number=$env{'form.number'};
                   8999:     if ($gradingmechanism ne 'attendance') {
1.414     www      9000:        foreach my $key (keys(%env)) {
                   9001:           if ($key=~/^form\.correct\:/) {
                   9002:              my @input=split(/\,/,$env{$key});
                   9003:              for (my $i=0;$i<=$#input;$i++) {
                   9004:                  if (($correct[$i]) && ($input[$i]) &&
                   9005:                      ($correct[$i] ne $input[$i])) {
                   9006:                     $result.='<br /><span class="LC_warning">'.
                   9007:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9008:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9009:                  } elsif ($input[$i]) {
                   9010:                     $correct[$i]=$input[$i];
                   9011:                  }
                   9012:              }
                   9013:           }
                   9014:        }
1.415     www      9015:        for (my $i=0;$i<$number;$i++) {
1.414     www      9016:           if (!$correct[$i]) {
                   9017:              $result.='<br /><span class="LC_error">'.
                   9018:                       &mt('No correct result given for question "[_1]"!',
                   9019:                           $env{'form.question:'.$i}).'</span>';
                   9020:           }
                   9021:        }
                   9022:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9023:     }
                   9024: # Start grading
1.415     www      9025:     my $pcorrect=$env{'form.pcorrect'};
                   9026:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9027:     my $storecount=0;
1.415     www      9028:     foreach my $key (keys(%env)) {
1.420     www      9029:        my $user='';
1.415     www      9030:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9031:           $user=$1;
                   9032:        }
                   9033:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9034:           my $id=$1;
                   9035:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9036:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9037:           } elsif ($env{'form.multi'.$id}) {
                   9038:              $user=$env{'form.multi'.$id};
1.420     www      9039:           }
                   9040:        }
                   9041:        if ($user) { 
1.415     www      9042:           my @answer=split(/\,/,$env{$key});
                   9043:           my $sum=0;
1.522     www      9044:           my $realnumber=$number;
1.415     www      9045:           for (my $i=0;$i<$number;$i++) {
                   9046:              if ($answer[$i]) {
                   9047:                 if ($gradingmechanism eq 'attendance') {
                   9048:                    $sum+=$pcorrect;
1.522     www      9049:                 } elsif ($answer[$i] eq '*') {
                   9050:                    $sum+=$pcorrect;
                   9051:                 } elsif ($answer[$i] eq '-') {
                   9052:                    $realnumber--;
1.415     www      9053:                 } else {
                   9054:                    if ($answer[$i] eq $correct[$i]) {
                   9055:                       $sum+=$pcorrect;
                   9056:                    } else {
                   9057:                       $sum+=$pincorrect;
                   9058:                    }
                   9059:                 }
                   9060:              }
                   9061:           }
1.522     www      9062:           my $ave=$sum/(100*$realnumber);
1.416     www      9063: # Store
                   9064:           my ($username,$domain)=split(/\:/,$user);
                   9065:           my %grades=();
                   9066:           $grades{"resource.$part.solved"}='correct_by_override';
                   9067:           $grades{"resource.$part.awarded"}=$ave;
                   9068:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9069:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9070:                                                  $env{'request.course.id'},
                   9071:                                                  $domain,$username);
                   9072:           if ($returncode ne 'ok') {
                   9073:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9074:           } else {
                   9075:              $storecount++;
                   9076:           }
1.415     www      9077:        }
                   9078:     }
                   9079: # We are done
1.549     hauer    9080:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9081:              '</td></tr></table>'."\n".
1.414     www      9082:              '</td></tr></table><br /><br />'."\n";
                   9083:     return $result.&show_grading_menu_form($symb);
                   9084: }
                   9085: 
1.1       albertel 9086: sub handler {
1.41      ng       9087:     my $request=$_[0];
1.434     albertel 9088:     &reset_caches();
1.257     albertel 9089:     if ($env{'browser.mathml'}) {
1.141     www      9090: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9091:     } else {
1.141     www      9092: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9093:     }
                   9094:     $request->send_http_header;
1.44      ng       9095:     return '' if $request->header_only;
1.41      ng       9096:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9097:     my $symb=&get_symb($request,1);
1.160     albertel 9098:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9099:     my $command=$commands[0];
1.447     foxr     9100: 
1.160     albertel 9101:     if ($#commands > 0) {
                   9102: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9103:     }
1.447     foxr     9104: 
1.513     foxr     9105:     $ssi_error = 0;
1.535     raeburn  9106:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9107:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9108:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9109:     if ($symb eq '' && $command eq '') {
1.257     albertel 9110: 	if ($env{'user.adv'}) {
                   9111: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9112: 		($env{'form.codethree'})) {
                   9113: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9114: 		    $env{'form.codethree'};
1.41      ng       9115: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9116: 		    &Apache::lonnet::checkin($token);
                   9117: 		if ($tsymb) {
1.137     albertel 9118: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9119: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9120: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9121: 					  ('grade_username' => $tuname,
                   9122: 					   'grade_domain' => $tudom,
                   9123: 					   'grade_courseid' => $tcrsid,
                   9124: 					   'grade_symb' => $tsymb)));
1.41      ng       9125: 		    } else {
1.45      ng       9126: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9127: 		    }
1.41      ng       9128: 		} else {
1.45      ng       9129: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9130: 		}
1.14      www      9131: 	    } else {
1.41      ng       9132: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9133: 	    }
                   9134: 	}
                   9135:     } else {
1.285     albertel 9136: 	&init_perm();
1.104     albertel 9137: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9138: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9139: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9140: 	    &pickStudentPage($request);
1.103     albertel 9141: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9142: 	    &displayPage($request);
1.104     albertel 9143: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9144: 	    &updateGradeByPage($request);
1.104     albertel 9145: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9146: 	    &processGroup($request);
1.104     albertel 9147: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9148: 	    $request->print(&grading_menu($request));
                   9149: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9150: 	    $request->print(&submit_options($request));
1.104     albertel 9151: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9152: 	    $request->print(&viewgrades($request));
1.104     albertel 9153: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9154: 	    $request->print(&processHandGrade($request));
1.106     albertel 9155: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9156: 	    $request->print(&editgrades($request));
1.106     albertel 9157: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9158: 	    $request->print(&verifyreceipt($request));
1.400     www      9159:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9160:             $request->print(&process_clicker($request));
                   9161:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9162:             $request->print(&process_clicker_file($request));
1.414     www      9163:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9164:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9165: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9166: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9167: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9168: 	    $request->print(&csvupload($request));
1.106     albertel 9169: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9170: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9171: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9172: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9173: 		$request->print(&csvuploadoptions($request));
1.41      ng       9174: 	    } else {
1.257     albertel 9175: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9176: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9177: 		} else {
1.257     albertel 9178: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9179: 		}
                   9180: 		$request->print(&csvuploadmap($request));
                   9181: 	    }
1.246     albertel 9182: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9183: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9184: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9185: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9186:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9187:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9188: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9189: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9190: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9191: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9192:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9193:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9194: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9195:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9196:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9197:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9198: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9199:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9200:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9201: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9202:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9203:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9204:             $request->print(&checkscantron_results($request));     
1.106     albertel 9205: 	} elsif ($command) {
1.562     bisitz   9206: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9207: 	}
1.2       albertel 9208:     }
1.513     foxr     9209:     if ($ssi_error) {
                   9210: 	&ssi_print_error($request);
                   9211:     }
1.353     albertel 9212:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9213:     &reset_caches();
1.44      ng       9214:     return '';
                   9215: }
                   9216: 
1.1       albertel 9217: 1;
                   9218: 
1.13      albertel 9219: __END__;
1.531     jms      9220: 
                   9221: 
                   9222: =head1 NAME
                   9223: 
                   9224: Apache::grades
                   9225: 
                   9226: =head1 SYNOPSIS
                   9227: 
                   9228: Handles the viewing of grades.
                   9229: 
                   9230: This is part of the LearningOnline Network with CAPA project
                   9231: described at http://www.lon-capa.org.
                   9232: 
                   9233: =head1 OVERVIEW
                   9234: 
                   9235: Do an ssi with retries:
                   9236: While I'd love to factor out this with the vesrion in lonprintout,
                   9237: 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
                   9238: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9239: 
                   9240: At least the logic that drives this has been pulled out into loncommon.
                   9241: 
                   9242: 
                   9243: 
                   9244: ssi_with_retries - Does the server side include of a resource.
                   9245:                      if the ssi call returns an error we'll retry it up to
                   9246:                      the number of times requested by the caller.
                   9247:                      If we still have a proble, no text is appended to the
                   9248:                      output and we set some global variables.
                   9249:                      to indicate to the caller an SSI error occurred.  
                   9250:                      All of this is supposed to deal with the issues described
                   9251:                      in LonCAPA BZ 5631 see:
                   9252:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9253:                      by informing the user that this happened.
                   9254: 
                   9255: Parameters:
                   9256:   resource   - The resource to include.  This is passed directly, without
                   9257:                interpretation to lonnet::ssi.
                   9258:   form       - The form hash parameters that guide the interpretation of the resource
                   9259:                
                   9260:   retries    - Number of retries allowed before giving up completely.
                   9261: Returns:
                   9262:   On success, returns the rendered resource identified by the resource parameter.
                   9263: Side Effects:
                   9264:   The following global variables can be set:
                   9265:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9266:                               It is up to the caller to initialize this to false
                   9267:                               if desired.
                   9268:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9269:                               of the resource that could not be rendered by the ssi
                   9270:                               call.
                   9271:    ssi_error_message   - The error string fetched from the ssi response
                   9272:                               in the event of an error.
                   9273: 
                   9274: 
                   9275: =head1 HANDLER SUBROUTINE
                   9276: 
                   9277: ssi_with_retries()
                   9278: 
                   9279: =head1 SUBROUTINES
                   9280: 
                   9281: =over
                   9282: 
                   9283: =item scantron_get_correction() : 
                   9284: 
                   9285:    Builds the interface screen to interact with the operator to fix a
                   9286:    specific error condition in a specific scanline
                   9287: 
                   9288:  Arguments:
                   9289:     $r           - Apache request object
                   9290:     $i           - number of the current scanline
                   9291:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9292:     $scan_config - hash ref as returned from &get_scantron_config()
                   9293:     $line        - full contents of the current scanline
                   9294:     $error       - error condition, valid values are
                   9295:                    'incorrectCODE', 'duplicateCODE',
                   9296:                    'doublebubble', 'missingbubble',
                   9297:                    'duplicateID', 'incorrectID'
                   9298:     $arg         - extra information needed
                   9299:        For errors:
                   9300:          - duplicateID   - paper number that this studentID was seen before on
                   9301:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9302:                            seen on before
                   9303:          - incorrectCODE - current incorrect CODE 
                   9304:          - doublebubble  - array ref of the bubble lines that have double
                   9305:                            bubble errors
                   9306:          - missingbubble - array ref of the bubble lines that have missing
                   9307:                            bubble errors
                   9308: 
                   9309: =item  scantron_get_maxbubble() : 
                   9310: 
                   9311:    Returns the maximum number of bubble lines that are expected to
                   9312:    occur. Does this by walking the selected sequence rendering the
                   9313:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9314:    for what the current value of the problem counter is.
                   9315: 
                   9316:    Caches the results to $env{'form.scantron_maxbubble'},
                   9317:    $env{'form.scantron.bubble_lines.n'}, 
                   9318:    $env{'form.scantron.first_bubble_line.n'} and
                   9319:    $env{"form.scantron.sub_bubblelines.n"}
                   9320:    which are the total number of bubble, lines, the number of bubble
                   9321:    lines for response n and number of the first bubble line for response n,
                   9322:    and a comma separated list of numbers of bubble lines for sub-questions
                   9323:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9324: 
                   9325: 
                   9326: =item  scantron_validate_missingbubbles() : 
                   9327: 
                   9328:    Validates all scanlines in the selected file to not have any
                   9329:     answers that don't have bubbles that have not been verified
                   9330:     to be bubble free.
                   9331: 
                   9332: =item  scantron_process_students() : 
                   9333: 
                   9334:    Routine that does the actual grading of the bubble sheet information.
                   9335: 
                   9336:    The parsed scanline hash is added to %env 
                   9337: 
                   9338:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9339:    foreach resource , with the form data of
                   9340: 
                   9341: 	'submitted'     =>'scantron' 
                   9342: 	'grade_target'  =>'grade',
                   9343: 	'grade_username'=> username of student
                   9344: 	'grade_domain'  => domain of student
                   9345: 	'grade_courseid'=> of course
                   9346: 	'grade_symb'    => symb of resource to grade
                   9347: 
                   9348:     This triggers a grading pass. The problem grading code takes care
                   9349:     of converting the bubbled letter information (now in %env) into a
                   9350:     valid submission.
                   9351: 
                   9352: =item  scantron_upload_scantron_data() :
                   9353: 
                   9354:     Creates the screen for adding a new bubble sheet data file to a course.
                   9355: 
                   9356: =item  scantron_upload_scantron_data_save() : 
                   9357: 
                   9358:    Adds a provided bubble information data file to the course if user
                   9359:    has the correct privileges to do so. 
                   9360: 
                   9361: =item  valid_file() :
                   9362: 
                   9363:    Validates that the requested bubble data file exists in the course.
                   9364: 
                   9365: =item  scantron_download_scantron_data() : 
                   9366: 
                   9367:    Shows a list of the three internal files (original, corrected,
                   9368:    skipped) for a specific bubble sheet data file that exists in the
                   9369:    course.
                   9370: 
                   9371: =item  scantron_validate_ID() : 
                   9372: 
                   9373:    Validates all scanlines in the selected file to not have any
1.556     weissno  9374:    invalid or underspecified student/employee IDs
1.531     jms      9375: 
                   9376: =back
                   9377: 
                   9378: =cut

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