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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.570   ! www         4: # $Id: grades.pm,v 1.569 2009/05/06 16:19:26 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.427     albertel 2138: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2139: 				    $osim,
                   2140: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2141: 				    $oname,$odom,
1.426     albertel 2142: 				    $old_course_desc{'description'},
1.427     albertel 2143: 				    $old_course_desc{'num'},
1.426     albertel 2144: 				    $old_course_desc{'domain'}).
1.398     albertel 2145: 				'</span></h3><blockquote><i>'.
1.151     albertel 2146: 				&keywords_highlight($oessay).
                   2147: 				'</i></blockquote><hr />';
                   2148: 			}
1.150     albertel 2149: 		    }
1.151     albertel 2150: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2151: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2152: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2153: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2154: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2155: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2156: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2157: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2158: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2159: 			if (@$files) {
1.544     raeburn  2160: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
1.303     banghart 2161: 			    my $file_counter = 0;
1.313     banghart 2162: 			    foreach my $file (@$files) {
1.468     albertel 2163: 			        $file_counter++;
1.232     albertel 2164: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.564     bisitz   2165: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
1.232     albertel 2166: 			    }
1.236     albertel 2167: 			    $lastsubonly.='<br />';
1.41      ng       2168: 			}
1.468     albertel 2169: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2170: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
1.555     raeburn  2171: 					 $respid,\%record,$order,undef,$uname,$udom);
1.151     albertel 2172: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2173: 			$lastsubonly.='</div>';
1.41      ng       2174: 		    }
                   2175: 		}
                   2176: 	    }
1.468     albertel 2177: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2178: 	}
                   2179: 	$request->print($lastsubonly);
1.468     albertel 2180:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2181: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2182: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2183:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2184: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2185: 								 $env{'request.course.id'},
1.44      ng       2186: 								 $last,'.submission',
                   2187: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2188:     }
1.120     ng       2189: 
1.121     ng       2190:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2191: 	.$udom.'" />'."\n");
1.44      ng       2192:     # return if view submission with no grading option
1.257     albertel 2193:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2194: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2195: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2196: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2197: 	$toGrade.='</div>'."\n";
1.257     albertel 2198: 	if (($env{'form.command'} eq 'submission') || 
                   2199: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2200: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2201: 	}
1.180     albertel 2202: 	$request->print($toGrade);
1.41      ng       2203: 	return;
1.180     albertel 2204:     } else {
1.468     albertel 2205: 	$request->print('</div>'."\n");
1.41      ng       2206:     }
1.33      ng       2207: 
1.121     ng       2208:     # essay grading message center
1.257     albertel 2209:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2210: 	my $result='<div class="LC_grade_message_center">';
                   2211:     
                   2212: 	$result.='<div class="LC_grade_message_center_header">'.
                   2213: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2214: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2215: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2216: 	if (scalar(@$col_fullnames) > 0) {
                   2217: 	    my $lastone = pop(@$col_fullnames);
                   2218: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2219: 	}
                   2220: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2221: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2222: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2223: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2224: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2225: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2226: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2227: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2228: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2229: 	    '<br />&nbsp;('.
1.468     albertel 2230: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2231: 	$result.='</div></div>';
1.121     ng       2232: 	$request->print($result);
1.118     ng       2233:     }
1.41      ng       2234: 
                   2235:     my %seen = ();
                   2236:     my @partlist;
1.129     ng       2237:     my @gradePartRespid;
1.375     albertel 2238:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2239:     $request->print('<div class="LC_grade_assign">'.
                   2240: 		    
                   2241: 		    '<div class="LC_grade_assign_header">'.
                   2242: 		    &mt('Assign Grades').'</div>'.
                   2243: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2244:     foreach my $part_response_id (@part_response_id) {
                   2245:     	my ($partid,$respid) = @{ $part_response_id };
                   2246: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2247: 	next if ($seen{$partid} > 0);
1.41      ng       2248: 	$seen{$partid}++;
1.393     albertel 2249: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2250: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2251: 	push(@partlist,$partid);
                   2252: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2253: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2254:     }
1.468     albertel 2255:     $request->print('</div></div>');
                   2256: 
                   2257:     $request->print('<div class="LC_grade_info_links">');
                   2258:     if ($perm{'vgr'}) {
                   2259: 	$request->print(
                   2260: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2261: 						   $uname,$udom,'check'));
                   2262:     }
                   2263:     if ($perm{'opa'}) {
                   2264: 	$request->print(
                   2265: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2266: 					 $uname,$udom,$symb,'check'));
                   2267:     }
                   2268:     $request->print('</div>');
                   2269: 
1.45      ng       2270:     $result='<input type="hidden" name="partlist'.$counter.
                   2271: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2272:     $result.='<input type="hidden" name="gradePartRespid'.
                   2273: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2274:     my $ctr = 0;
                   2275:     while ($ctr < scalar(@partlist)) {
                   2276: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2277: 	    $partlist[$ctr].'" />'."\n";
                   2278: 	$ctr++;
                   2279:     }
1.468     albertel 2280:     $request->print($result.''."\n");
1.41      ng       2281: 
1.441     www      2282: # Done with printing info for one student
                   2283: 
1.468     albertel 2284:     $request->print('</div>');#LC_grade_show_user_body
                   2285:     $request->print('</div>');#LC_grade_show_user
1.441     www      2286: 
                   2287: 
1.41      ng       2288:     # print end of form
                   2289:     if ($counter == $total) {
1.297     www      2290: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2291: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2292: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2293: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2294: 	my $ntstu ='<select name="NTSTU">'.
                   2295: 	    '<option>1</option><option>2</option>'.
                   2296: 	    '<option>3</option><option>5</option>'.
                   2297: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2298: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2299: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.549     hauer    2300: 	$endform.=&mt('[quant,_1,student]',$ntstu);
1.485     albertel 2301: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2302: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2303: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2304: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2305: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2306:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2307:             "' name='increment' />";
1.485     albertel 2308: 	$endform.='</td></tr></table></form>';
1.324     albertel 2309: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2310: 	$request->print($endform);
                   2311:     }
                   2312:     return '';
1.38      ng       2313: }
                   2314: 
1.464     albertel 2315: sub check_collaborators {
                   2316:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2317:     my ($result,@col_fullnames);
                   2318:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2319:     foreach my $part (keys(%$handgrade)) {
                   2320: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2321: 					'.maxcollaborators',
                   2322: 					$symb,$udom,$uname);
                   2323: 	next if ($ncol <= 0);
                   2324: 	$part =~ s/\_/\./g;
                   2325: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2326: 	my (@good_collaborators, @bad_collaborators);
                   2327: 	foreach my $possible_collaborator
                   2328: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2329: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2330: 	    next if ($possible_collaborator eq '');
                   2331: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2332: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2333: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2334: 	    # Doing this grep allows 'fuzzy' specification
                   2335: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2336: 			       keys(%$classlist));
                   2337: 	    if (! scalar(@matches)) {
                   2338: 		push(@bad_collaborators, $possible_collaborator);
                   2339: 	    } else {
                   2340: 		push(@good_collaborators, @matches);
                   2341: 	    }
                   2342: 	}
                   2343: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2344: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2345: 	    foreach my $name (@good_collaborators) {
                   2346: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2347: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2348: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2349: 	    }
                   2350: 	    $result.='<br />'."\n";
1.466     albertel 2351: 	    my ($part)=split(/\./,$part);
1.464     albertel 2352: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2353: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2354: 		"\n";
                   2355: 	}
                   2356: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2357: 	    $result.='<div class="LC_warning">';
1.464     albertel 2358: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2359: 	    $result .= '</div>';
                   2360: 	}         
                   2361: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2362: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2363: 	    $result .= &mt('This student has submitted too many '.
                   2364: 		'collaborators.  Maximum is [_1].',$ncol);
                   2365: 	    $result .= '</div>';
                   2366: 	}
                   2367:     }
                   2368:     return ($result,$fullname,\@col_fullnames);
                   2369: }
                   2370: 
1.44      ng       2371: #--- Retrieve the last submission for all the parts
1.38      ng       2372: sub get_last_submission {
1.119     ng       2373:     my ($returnhash)=@_;
1.46      ng       2374:     my (@string,$timestamp);
1.119     ng       2375:     if ($$returnhash{'version'}) {
1.46      ng       2376: 	my %lasthash=();
                   2377: 	my ($version);
1.119     ng       2378: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2379: 	    foreach my $key (sort(split(/\:/,
                   2380: 					$$returnhash{$version.':keys'}))) {
                   2381: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2382: 		$timestamp = 
1.545     raeburn  2383: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2384: 	    }
                   2385: 	}
1.397     albertel 2386: 	foreach my $key (keys(%lasthash)) {
                   2387: 	    next if ($key !~ /\.submission$/);
                   2388: 
                   2389: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2390: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2391: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2392: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2393: 	}
                   2394:     }
1.397     albertel 2395:     if (!@string) {
                   2396: 	$string[0] =
1.539     riegler  2397: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2398:     }
                   2399:     return (\@string,\$timestamp);
1.38      ng       2400: }
1.35      ng       2401: 
1.44      ng       2402: #--- High light keywords, with style choosen by user.
1.38      ng       2403: sub keywords_highlight {
1.44      ng       2404:     my $string    = shift;
1.257     albertel 2405:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2406:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2407:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2408:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2409:     foreach my $keyword (@keylist) {
                   2410: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2411:     }
                   2412:     return $string;
1.38      ng       2413: }
1.36      ng       2414: 
1.44      ng       2415: #--- Called from submission routine
1.38      ng       2416: sub processHandGrade {
1.41      ng       2417:     my ($request) = shift;
1.324     albertel 2418:     my $symb   = &get_symb($request);
                   2419:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2420:     my $button = $env{'form.gradeOpt'};
                   2421:     my $ngrade = $env{'form.NCT'};
                   2422:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2423:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2424:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2425: 
1.44      ng       2426:     if ($button eq 'Save & Next') {
                   2427: 	my $ctr = 0;
                   2428: 	while ($ctr < $ngrade) {
1.257     albertel 2429: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2430: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2431: 	    if ($errorflag eq 'no_score') {
                   2432: 		$ctr++;
                   2433: 		next;
                   2434: 	    }
1.104     albertel 2435: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2436: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2437: 		$ctr++;
                   2438: 		next;
                   2439: 	    }
1.257     albertel 2440: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2441: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2442: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2443:             my ($feedurl,$showsymb) =
                   2444: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2445: 	    my $messagetail;
1.62      albertel 2446: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2447: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2448: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2449: 		$subject.=' ['.$restitle.']';
1.44      ng       2450: 		my (@msgnum) = split(/,/,$includemsg);
                   2451: 		foreach (@msgnum) {
1.257     albertel 2452: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2453: 		}
1.80      ng       2454: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2455: 		if ($env{'form.withgrades'.$ctr}) {
                   2456: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2457: 		    $messagetail = " for <a href=\"".
1.418     albertel 2458: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2459: 		}
                   2460: 		$msgstatus = 
                   2461:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2462: 						     $message.$messagetail,
1.418     albertel 2463:                                                      undef,$feedurl,undef,
1.386     raeburn  2464:                                                      undef,undef,$showsymb,
                   2465:                                                      $restitle);
                   2466: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2467: 				$msgstatus);
1.44      ng       2468: 	    }
1.257     albertel 2469: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2470: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2471: 		foreach my $collabstr (@collabstrs) {
                   2472: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2473: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2474: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2475: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2476: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2477: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2478: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2479: 			    next;
1.418     albertel 2480: 			} elsif ($message ne '') {
                   2481: 			    my ($baseurl,$showsymb) = 
                   2482: 				&get_feedurl_and_symb($symb,$collaborator,
                   2483: 						      $udom);
                   2484: 			    if ($env{'form.withgrades'.$ctr}) {
                   2485: 				$messagetail = " for <a href=\"".
1.386     raeburn  2486:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2487: 			    }
1.418     albertel 2488: 			    $msgstatus = 
                   2489: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2490: 			}
1.44      ng       2491: 		    }
                   2492: 		}
                   2493: 	    }
                   2494: 	    $ctr++;
                   2495: 	}
                   2496:     }
                   2497: 
1.257     albertel 2498:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2499: 	# Keywords sorted in alphabatical order
1.257     albertel 2500: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2501: 	my %keyhash = ();
1.257     albertel 2502: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2503: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2504: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2505: 	$env{'form.keywords'} = join(' ',@keywords);
                   2506: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2507: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2508: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2509: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2510: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2511: 
                   2512: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2513: 	# New messages are saved in env for the next student.
1.119     ng       2514: 	# All messages are saved in nohist_handgrade.db
                   2515: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2516: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2517: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2518: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2519: 		$idx++;
                   2520: 	    }
                   2521: 	    $ctr++;
1.41      ng       2522: 	}
1.119     ng       2523: 	$ctr = 0;
                   2524: 	while ($ctr < $ngrade) {
1.257     albertel 2525: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2526: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2527: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2528: 		$idx++;
                   2529: 	    }
                   2530: 	    $ctr++;
1.41      ng       2531: 	}
1.257     albertel 2532: 	$env{'form.savemsgN'} = --$idx;
                   2533: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2534: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2535: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2536:     }
1.44      ng       2537:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2538:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2539:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2540: 	my ($ctr,$total) = (0,0);
                   2541: 	while ($ctr < $ngrade) {
1.257     albertel 2542: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2543: 	    $ctr++;
                   2544: 	}
1.257     albertel 2545: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2546: 	$ctr = 0;
                   2547: 	while ($ctr < $total) {
1.257     albertel 2548: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2549: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2550: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2551: 	    &submission($request,$ctr,$total-1);
1.41      ng       2552: 	    $ctr++;
                   2553: 	}
                   2554: 	return '';
                   2555:     }
1.36      ng       2556: 
1.121     ng       2557: # Go directly to grade student - from submission or link from chart page
1.120     ng       2558:     if ($button eq 'Grade Student') {
1.324     albertel 2559: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2560: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2561: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2562: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2563: 	&submission($request,0,0);
                   2564: 	return '';
                   2565:     }
                   2566: 
1.44      ng       2567:     # Get the next/previous one or group of students
1.257     albertel 2568:     my $firststu = $env{'form.unamedom0'};
                   2569:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2570:     my $ctr = 2;
1.41      ng       2571:     while ($laststu eq '') {
1.257     albertel 2572: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2573: 	$ctr++;
                   2574: 	$laststu = $firststu if ($ctr > $ngrade);
                   2575:     }
1.44      ng       2576: 
1.41      ng       2577:     my (@parsedlist,@nextlist);
                   2578:     my ($nextflg) = 0;
1.524     raeburn  2579:     foreach my $item (sort 
1.294     albertel 2580: 	     {
                   2581: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2582: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2583: 		 }
                   2584: 		 return $a cmp $b;
                   2585: 	     } (keys(%$fullname))) {
1.41      ng       2586: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2587: 	    push(@parsedlist,$item);
1.41      ng       2588: 	}
1.524     raeburn  2589: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2590: 	if ($button eq 'Previous') {
1.524     raeburn  2591: 	    last if ($item eq $firststu);
                   2592: 	    push(@parsedlist,$item);
1.41      ng       2593: 	}
                   2594:     }
                   2595:     $ctr = 0;
                   2596:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2597:     my ($partlist) = &response_type($symb);
1.41      ng       2598:     foreach my $student (@parsedlist) {
1.257     albertel 2599: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2600: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2601: 	
                   2602: 	if ($submitonly eq 'queued') {
                   2603: 	    my %queue_status = 
                   2604: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2605: 							$udom,$uname);
                   2606: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2607: 	}
                   2608: 
1.156     albertel 2609: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2610: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2611: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2612: 	    my $submitted = 0;
1.248     albertel 2613: 	    my $ungraded = 0;
                   2614: 	    my $incorrect = 0;
1.524     raeburn  2615: 	    foreach my $item (keys(%status)) {
                   2616: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2617: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2618: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2619: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2620: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2621: 		    $submitted = 0;
                   2622: 		}
1.41      ng       2623: 	    }
1.156     albertel 2624: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2625: 				     $submitonly eq 'incorrect' ||
                   2626: 				     $submitonly eq 'graded'));
1.248     albertel 2627: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2628: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2629: 	}
1.524     raeburn  2630: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2631: 	last if ($ctr == $ntstu);
1.41      ng       2632: 	$ctr++;
                   2633:     }
1.36      ng       2634: 
1.41      ng       2635:     $ctr = 0;
                   2636:     my $total = scalar(@nextlist)-1;
1.39      ng       2637: 
1.524     raeburn  2638:     foreach (sort(@nextlist)) {
1.41      ng       2639: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2640: 	$env{'form.student'}  = $uname;
                   2641: 	$env{'form.userdom'}  = $udom;
                   2642: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2643: 	&submission($request,$ctr,$total);
                   2644: 	$ctr++;
                   2645:     }
                   2646:     if ($total < 0) {
1.485     albertel 2647: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2648: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2649: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2650: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2651: 	$request->print($the_end);
                   2652:     }
                   2653:     return '';
1.38      ng       2654: }
1.36      ng       2655: 
1.44      ng       2656: #---- Save the score and award for each student, if changed
1.38      ng       2657: sub saveHandGrade {
1.324     albertel 2658:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2659:     my @version_parts;
1.104     albertel 2660:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2661: 					   $env{'request.course.id'});
1.104     albertel 2662:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2663:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2664:     my @parts_graded;
1.77      ng       2665:     my %newrecord  = ();
                   2666:     my ($pts,$wgt) = ('','');
1.269     raeburn  2667:     my %aggregate = ();
                   2668:     my $aggregateflag = 0;
1.301     albertel 2669:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2670:     foreach my $new_part (@parts) {
1.337     banghart 2671: 	#collaborator ($submi may vary for different parts
1.259     banghart 2672: 	if ($submitter && $new_part ne $part) { next; }
                   2673: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2674: 	if ($dropMenu eq 'excused') {
1.259     banghart 2675: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2676: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2677: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2678: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2679: 		}
1.364     banghart 2680: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2681: 	    }
1.125     ng       2682: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2683: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2684: 	    foreach my $key (keys(%record)) {
1.259     banghart 2685: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2686: 	    }
1.259     banghart 2687: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2688: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2689:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2690: 
                   2691:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2692: 					       [$new_part]);
                   2693:             my $aggtries =$totaltries;
1.269     raeburn  2694:             if ($last_resets{$new_part}) {
1.270     albertel 2695:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2696: 					   $new_part);
1.269     raeburn  2697:             }
1.270     albertel 2698: 
                   2699:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2700:             if ($aggtries > 0) {
1.327     albertel 2701:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2702:                 $aggregateflag = 1;
                   2703:             }
1.125     ng       2704: 	} elsif ($dropMenu eq '') {
1.259     banghart 2705: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2706: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2707: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2708: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2709: 		next;
                   2710: 	    }
1.259     banghart 2711: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2712: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2713: 	    my $partial= $pts/$wgt;
1.259     banghart 2714: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2715: 		#do not update score for part if not changed.
1.346     banghart 2716:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2717: 		next;
1.251     banghart 2718: 	    } else {
1.524     raeburn  2719: 	        push(@parts_graded,$new_part);
1.153     albertel 2720: 	    }
1.259     banghart 2721: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2722: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2723: 	    }
1.259     banghart 2724: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2725: 	    if ($partial == 0) {
1.153     albertel 2726: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2727: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2728: 		}
1.41      ng       2729: 	    } else {
1.153     albertel 2730: 		if ($record{$reckey} ne 'correct_by_override') {
                   2731: 		    $newrecord{$reckey} = 'correct_by_override';
                   2732: 		}
                   2733: 	    }	    
                   2734: 	    if ($submitter && 
1.259     banghart 2735: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2736: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2737: 	    }
1.259     banghart 2738: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2739: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2740: 	}
1.259     banghart 2741: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2742: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2743: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2744: 	        $dropMenu eq 'reset status')
                   2745: 	   {
1.524     raeburn  2746: 	    push(@version_parts,$new_part);
1.259     banghart 2747: 	}
1.41      ng       2748:     }
1.301     albertel 2749:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2750:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2751: 
1.344     albertel 2752:     if (%newrecord) {
                   2753:         if (@version_parts) {
1.364     banghart 2754:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2755:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2756: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2757: 	    foreach my $new_part (@version_parts) {
                   2758: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2759: 				$new_part,\%newrecord);
                   2760: 	    }
1.259     banghart 2761:         }
1.44      ng       2762: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2763: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2764: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2765: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2766:     }
1.269     raeburn  2767:     if ($aggregateflag) {
                   2768:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2769: 			      $cdom,$cnum);
1.269     raeburn  2770:     }
1.301     albertel 2771:     return ('',$pts,$wgt);
1.36      ng       2772: }
1.322     albertel 2773: 
1.380     albertel 2774: sub check_and_remove_from_queue {
                   2775:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2776:     my @ungraded_parts;
                   2777:     foreach my $part (@{$parts}) {
                   2778: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2779: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2780: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2781: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2782: 		) {
                   2783: 	    push(@ungraded_parts, $part);
                   2784: 	}
                   2785:     }
                   2786:     if ( !@ungraded_parts ) {
                   2787: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2788: 					       $cnum,$domain,$stuname);
                   2789:     }
                   2790: }
                   2791: 
1.337     banghart 2792: sub handback_files {
                   2793:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2794:     my $portfolio_root = '/userfiles/portfolio';
1.359     www      2795:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2796: 
                   2797:     my @part_response_id = &flatten_responseType($responseType);
                   2798:     foreach my $part_response_id (@part_response_id) {
                   2799:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2800: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2801:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2802:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2803:                 my $file_counter = 1;
1.367     albertel 2804: 		my $file_msg;
1.337     banghart 2805:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2806:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2807:                     my ($directory,$answer_file) = 
                   2808:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2809:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2810: 		        &file_name_version_ext($answer_file);
1.355     banghart 2811: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2812:                     my $getpropath = 1;
                   2813: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2814: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2815:                     # fix file name
                   2816:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2817:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2818:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2819:             	                                $save_file_name);
1.337     banghart 2820:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2821:                         $request->print('<br /><span class="LC_error">'.
                   2822:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2823:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2824:                                         '</span>');
1.356     banghart 2825:                     } else {
1.360     banghart 2826:                         # mark the file as read only
                   2827:                         my @files = ($save_file_name);
1.372     albertel 2828:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2829:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2830: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2831: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2832: 			}
                   2833:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2834: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2835: 
1.337     banghart 2836:                     }
                   2837:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2838:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2839:                     $file_counter++;
                   2840:                 }
1.367     albertel 2841: 		my $subject = "File Handed Back by Instructor ";
                   2842: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2843: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2844: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2845: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2846: 		my ($feedurl,$showsymb) = 
                   2847: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2848:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2849: 		my $msgstatus = 
                   2850:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2851: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2852:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2853:             }
                   2854:         }
1.338     banghart 2855:     return;
1.337     banghart 2856: }
                   2857: 
1.418     albertel 2858: sub get_feedurl_and_symb {
                   2859:     my ($symb,$uname,$udom) = @_;
                   2860:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2861:     $url = &Apache::lonnet::clutter($url);
                   2862:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2863: 					$symb,$udom,$uname);
                   2864:     if ($encrypturl =~ /^yes$/i) {
                   2865: 	&Apache::lonenc::encrypted(\$url,1);
                   2866: 	&Apache::lonenc::encrypted(\$symb,1);
                   2867:     }
                   2868:     return ($url,$symb);
                   2869: }
                   2870: 
1.313     banghart 2871: sub get_submitted_files {
                   2872:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2873:     my @files;
                   2874:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2875:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2876:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2877:     	    push(@files,$file_url.$file);
                   2878:         }
                   2879:     }
                   2880:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2881:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2882:     }
                   2883:     return (\@files);
                   2884: }
1.322     albertel 2885: 
1.269     raeburn  2886: # ----------- Provides number of tries since last reset.
                   2887: sub get_num_tries {
                   2888:     my ($record,$last_reset,$part) = @_;
                   2889:     my $timestamp = '';
                   2890:     my $num_tries = 0;
                   2891:     if ($$record{'version'}) {
                   2892:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2893:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2894:                 $timestamp = $$record{$version.':timestamp'};
                   2895:                 if ($timestamp > $last_reset) {
                   2896:                     $num_tries ++;
                   2897:                 } else {
                   2898:                     last;
                   2899:                 }
                   2900:             }
                   2901:         }
                   2902:     }
                   2903:     return $num_tries;
                   2904: }
                   2905: 
                   2906: # ----------- Determine decrements required in aggregate totals 
                   2907: sub decrement_aggs {
                   2908:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2909:     my %decrement = (
                   2910:                         attempts => 0,
                   2911:                         users => 0,
                   2912:                         correct => 0
                   2913:                     );
                   2914:     $decrement{'attempts'} = $aggtries;
                   2915:     if ($solvedstatus =~ /^correct/) {
                   2916:         $decrement{'correct'} = 1;
                   2917:     }
                   2918:     if ($aggtries == $totaltries) {
                   2919:         $decrement{'users'} = 1;
                   2920:     }
1.524     raeburn  2921:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2922:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2923:     }
                   2924:     return;
                   2925: }
                   2926: 
                   2927: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2928: sub get_last_resets {
1.270     albertel 2929:     my ($symb,$courseid,$partids) =@_;
                   2930:     my %last_resets;
1.269     raeburn  2931:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2932:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2933:     my @keys;
                   2934:     foreach my $part (@{$partids}) {
                   2935: 	push(@keys,"$symb\0$part\0resettime");
                   2936:     }
                   2937:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2938: 				     $cdom,$cname);
                   2939:     foreach my $part (@{$partids}) {
                   2940: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2941:     }
1.270     albertel 2942:     return %last_resets;
1.269     raeburn  2943: }
                   2944: 
1.251     banghart 2945: # ----------- Handles creating versions for portfolio files as answers
                   2946: sub version_portfiles {
1.343     banghart 2947:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2948:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2949:     my @returned_keys;
1.255     banghart 2950:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2951:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2952:     foreach my $key (keys(%$record)) {
1.259     banghart 2953:         my $new_portfiles;
1.263     banghart 2954:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2955:             my @versioned_portfiles;
1.367     albertel 2956:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2957:             foreach my $file (@portfiles) {
1.306     banghart 2958:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2959:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2960: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2961: 		    &file_name_version_ext($answer_file);
1.517     raeburn  2962:                 my $getpropath = 1;    
                   2963:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 2964:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2965:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2966:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2967:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2968:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2969:                         [$directory.$new_answer],
1.306     banghart 2970:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2971:                 }
1.252     banghart 2972:             }
1.343     banghart 2973:             $$record{$key} = join(',',@versioned_portfiles);
                   2974:             push(@returned_keys,$key);
1.251     banghart 2975:         }
                   2976:     } 
1.343     banghart 2977:     return (@returned_keys);   
1.305     banghart 2978: }
                   2979: 
1.307     banghart 2980: sub get_next_version {
1.341     banghart 2981:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2982:     my $version;
                   2983:     foreach my $row (@$dir_list) {
                   2984:         my ($file) = split(/\&/,$row,2);
                   2985:         my ($file_name,$file_version,$file_ext) =
                   2986: 	    &file_name_version_ext($file);
                   2987:         if (($file_name eq $answer_name) && 
                   2988: 	    ($file_ext eq $answer_ext)) {
                   2989:                 # gets here if filename and extension match, regardless of version
                   2990:                 if ($file_version ne '') {
                   2991:                 # a versioned file is found  so save it for later
                   2992:                 if ($file_version > $version) {
                   2993: 		    $version = $file_version;
                   2994: 	        }
                   2995:             }
                   2996:         }
                   2997:     } 
                   2998:     $version ++;
                   2999:     return($version);
                   3000: }
                   3001: 
1.305     banghart 3002: sub version_selected_portfile {
1.306     banghart 3003:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3004:     my ($answer_name,$answer_ver,$answer_ext) =
                   3005:         &file_name_version_ext($file_name);
                   3006:     my $new_answer;
                   3007:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3008:     if($env{'form.copy'} eq '-1') {
                   3009:         $new_answer = 'problem getting file';
                   3010:     } else {
                   3011:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3012:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3013:                             $stu_name,$domain,'copy',
                   3014: 		        '/portfolio'.$directory.$new_answer);
                   3015:     }    
                   3016:     return ($new_answer);
1.251     banghart 3017: }
                   3018: 
1.304     albertel 3019: sub file_name_version_ext {
                   3020:     my ($file)=@_;
                   3021:     my @file_parts = split(/\./, $file);
                   3022:     my ($name,$version,$ext);
                   3023:     if (@file_parts > 1) {
                   3024: 	$ext=pop(@file_parts);
                   3025: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3026: 	    $version=pop(@file_parts);
                   3027: 	}
                   3028: 	$name=join('.',@file_parts);
                   3029:     } else {
                   3030: 	$name=join('.',@file_parts);
                   3031:     }
                   3032:     return($name,$version,$ext);
                   3033: }
                   3034: 
1.44      ng       3035: #--------------------------------------------------------------------------------------
                   3036: #
                   3037: #-------------------------- Next few routines handles grading by section or whole class
                   3038: #
                   3039: #--- Javascript to handle grading by section or whole class
1.42      ng       3040: sub viewgrades_js {
                   3041:     my ($request) = shift;
                   3042: 
1.539     riegler  3043:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3044:     $request->print(<<VIEWJAVASCRIPT);
                   3045: <script type="text/javascript" language="javascript">
1.45      ng       3046:    function writePoint(partid,weight,point) {
1.125     ng       3047: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3048: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3049: 	if (point == "textval") {
1.125     ng       3050: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3051: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3052: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3053: 		var resetbox = false;
                   3054: 		for (var i=0; i<radioButton.length; i++) {
                   3055: 		    if (radioButton[i].checked) {
                   3056: 			textbox.value = i;
                   3057: 			resetbox = true;
                   3058: 		    }
                   3059: 		}
                   3060: 		if (!resetbox) {
                   3061: 		    textbox.value = "";
                   3062: 		}
                   3063: 		return;
                   3064: 	    }
1.109     matthew  3065: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3066: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3067: 				   ") greater than the weight for the part. Accept?");
                   3068: 		if (resp == false) {
                   3069: 		    textbox.value = "";
                   3070: 		    return;
                   3071: 		}
                   3072: 	    }
1.42      ng       3073: 	    for (var i=0; i<radioButton.length; i++) {
                   3074: 		radioButton[i].checked=false;
1.109     matthew  3075: 		if (parseFloat(point) == i) {
1.42      ng       3076: 		    radioButton[i].checked=true;
                   3077: 		}
                   3078: 	    }
1.41      ng       3079: 
1.42      ng       3080: 	} else {
1.125     ng       3081: 	    textbox.value = parseFloat(point);
1.42      ng       3082: 	}
1.41      ng       3083: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3084: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3085: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3086: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3087: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3088: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3089: 	    if (saveval != "correct") {
                   3090: 		scorename.value = point;
1.43      ng       3091: 		if (selname[0].selected != true) {
                   3092: 		    selname[0].selected = true;
                   3093: 		}
1.42      ng       3094: 	    }
                   3095: 	}
1.125     ng       3096: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3097:     }
                   3098: 
                   3099:     function writeRadText(partid,weight) {
1.125     ng       3100: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3101: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3102:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3103: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3104: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3105: 	    for (var i=0; i<radioButton.length; i++) {
                   3106: 		radioButton[i].checked=false;
                   3107: 
                   3108: 	    }
                   3109: 	    textbox.value = "";
                   3110: 
                   3111: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3112: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3113: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3114: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3115: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3116: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3117: 		if ((saveval != "correct") || override) {
1.42      ng       3118: 		    scorename.value = "";
1.125     ng       3119: 		    if (selval[1].selected) {
                   3120: 			selname[1].selected = true;
                   3121: 		    } else {
                   3122: 			selname[2].selected = true;
                   3123: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3124: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3125: 		    }
1.42      ng       3126: 		}
                   3127: 	    }
1.43      ng       3128: 	} else {
                   3129: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3130: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3131: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3132: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3133: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3134: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3135: 		if ((saveval != "correct") || override) {
1.125     ng       3136: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3137: 		    selname[0].selected = true;
                   3138: 		}
                   3139: 	    }
                   3140: 	}	    
1.42      ng       3141:     }
                   3142: 
                   3143:     function changeSelect(partid,user) {
1.125     ng       3144: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3145: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3146: 	var point  = textbox.value;
1.125     ng       3147: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3148: 
1.109     matthew  3149: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3150: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3151: 	    textbox.value = "";
                   3152: 	    return;
                   3153: 	}
1.109     matthew  3154: 	if (parseFloat(point) > parseFloat(weight)) {
                   3155: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3156: 			       ") greater than the weight of the part. Accept?");
                   3157: 	    if (resp == false) {
                   3158: 		textbox.value = "";
                   3159: 		return;
                   3160: 	    }
                   3161: 	}
1.42      ng       3162: 	selval[0].selected = true;
                   3163:     }
                   3164: 
                   3165:     function changeOneScore(partid,user) {
1.125     ng       3166: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3167: 	if (selval[1].selected || selval[2].selected) {
                   3168: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3169: 	    if (selval[2].selected) {
                   3170: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3171: 	    }
1.269     raeburn  3172:         }
1.42      ng       3173:     }
                   3174: 
                   3175:     function resetEntry(numpart) {
                   3176: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3177: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3178: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3179: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3180: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3181: 	    for (var i=0; i<radioButton.length; i++) {
                   3182: 		radioButton[i].checked=false;
                   3183: 
                   3184: 	    }
                   3185: 	    textbox.value = "";
                   3186: 	    selval[0].selected = true;
                   3187: 
                   3188: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3189: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3190: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3191: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3192: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3193: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3194: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3195: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3196: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3197: 		if (saveselval == "excused") {
1.43      ng       3198: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3199: 		} else {
1.43      ng       3200: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3201: 		}
                   3202: 	    }
1.41      ng       3203: 	}
1.42      ng       3204:     }
                   3205: 
1.41      ng       3206: </script>
                   3207: VIEWJAVASCRIPT
1.42      ng       3208: }
                   3209: 
1.44      ng       3210: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3211: sub viewgrades {
                   3212:     my ($request) = shift;
                   3213:     &viewgrades_js($request);
1.41      ng       3214: 
1.324     albertel 3215:     my ($symb) = &get_symb($request);
1.168     albertel 3216:     #need to make sure we have the correct data for later EXT calls, 
                   3217:     #thus invalidate the cache
                   3218:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3219:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3220:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3221:     &Apache::lonnet::clear_EXT_cache_status();
                   3222: 
1.398     albertel 3223:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3224:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3225: 
                   3226:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3227:     $result.=&jscriptNform($symb);
1.41      ng       3228: 
1.44      ng       3229:     #beginning of class grading form
1.442     banghart 3230:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3231:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3232: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3233: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3234: 	&build_section_inputs().
1.257     albertel 3235: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3236: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3237: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3238: 
1.560     raeburn  3239:     my ($common_header,$specific_header);
1.257     albertel 3240:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3241: 	$common_header = &mt('Assign Common Grade to Class');
                   3242:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3243:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3244:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3245: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3246:     } else {
1.560     raeburn  3247:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3248:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3249: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3250:     }
1.560     raeburn  3251:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3252:     #radio buttons/text box for assigning points for a section or class.
                   3253:     #handles different parts of a problem
1.375     albertel 3254:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3255:     my %weight = ();
                   3256:     my $ctsparts = 0;
1.45      ng       3257:     my %seen = ();
1.375     albertel 3258:     my @part_response_id = &flatten_responseType($responseType);
                   3259:     foreach my $part_response_id (@part_response_id) {
                   3260:     	my ($partid,$respid) = @{ $part_response_id };
                   3261: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3262: 	next if $seen{$partid};
                   3263: 	$seen{$partid}++;
1.375     albertel 3264: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3265: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3266: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3267: 
1.324     albertel 3268: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3269: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3270: 	my $ctr = 0;
1.42      ng       3271: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3272: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3273: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3274: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3275: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3276: 	    $ctr++;
                   3277: 	}
1.485     albertel 3278: 	$radio.='</tr></table>';
                   3279: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3280: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3281: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3282: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3283: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3284: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3285: 		$weight{$partid}.')"> '.
1.401     albertel 3286: 	    '<option selected="selected"> </option>'.
1.485     albertel 3287: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3288: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3289: 	    '</select></td>'.
                   3290:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3291: 	$line.='<input type="hidden" name="partid_'.
                   3292: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3293: 	$line.='<input type="hidden" name="weight_'.
                   3294: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3295: 
                   3296: 	$result.=
                   3297: 	    &Apache::loncommon::start_data_table_row()."\n".
1.539     riegler  3298: 	    '<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 3299: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3300: 	$ctsparts++;
1.41      ng       3301:     }
1.474     albertel 3302:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3303: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3304:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3305: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3306: 
1.44      ng       3307:     #table listing all the students in a section/class
                   3308:     #header of table
1.560     raeburn  3309:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3310:               &Apache::loncommon::start_data_table().
                   3311: 	      &Apache::loncommon::start_data_table_header_row().
                   3312: 	      '<th>'.&mt('No.').'</th>'.
                   3313: 	      '<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3314:     my (@parts) = sort(&getpartlist($symb));
                   3315:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3316:     my @partids = ();
1.41      ng       3317:     foreach my $part (@parts) {
                   3318: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3319:         my $narrowtext = &mt('Tries');
                   3320: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3321: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3322: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3323:         push(@partids,$partid);
1.324     albertel 3324: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3325: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3326: 	    $result.='<th>'.
                   3327: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3328: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3329: 	    next;
1.485     albertel 3330: 	    
1.207     albertel 3331: 	} else {
1.485     albertel 3332: 	    if ($display =~ /Problem Status/) {
                   3333: 		my $grade_status_mt = &mt('Grade Status');
                   3334: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3335: 	    }
                   3336: 	    my $part_mt = &mt('Part:');
                   3337: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3338: 	}
1.485     albertel 3339: 
1.474     albertel 3340: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3341:     }
1.474     albertel 3342:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3343: 
1.270     albertel 3344:     my %last_resets = 
                   3345: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3346: 
1.41      ng       3347:     #get info for each student
1.44      ng       3348:     #list all the students - with points and grade status
1.257     albertel 3349:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3350:     my $ctr = 0;
1.294     albertel 3351:     foreach (sort 
                   3352: 	     {
                   3353: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3354: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3355: 		 }
                   3356: 		 return $a cmp $b;
                   3357: 	     } (keys(%$fullname))) {
1.126     ng       3358: 	$ctr++;
1.324     albertel 3359: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3360: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3361:     }
1.474     albertel 3362:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3363:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3364:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3365: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3366:     if (scalar(%$fullname) eq 0) {
                   3367: 	my $colspan=3+scalar(@parts);
1.433     banghart 3368: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3369:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3370: 	$result='<span class="LC_warning">'.
1.485     albertel 3371: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3372: 	        $section_display, $stu_status).
1.433     banghart 3373: 	    '</span>';
1.96      albertel 3374:     }
1.324     albertel 3375:     $result.=&show_grading_menu_form($symb);
1.41      ng       3376:     return $result;
                   3377: }
                   3378: 
1.44      ng       3379: #--- call by previous routine to display each student
1.41      ng       3380: sub viewstudentgrade {
1.324     albertel 3381:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3382:     my ($uname,$udom) = split(/:/,$student);
                   3383:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3384:     my %aggregates = (); 
1.474     albertel 3385:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3386: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3387: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3388: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3389: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3390: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3391:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3392:     foreach my $apart (@$parts) {
                   3393: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3394: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3395:         $result.='<td align="center">';
1.269     raeburn  3396:         my ($aggtries,$totaltries);
                   3397:         unless (exists($aggregates{$part})) {
1.270     albertel 3398: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3399: 
                   3400: 	    $aggtries = $totaltries;
1.269     raeburn  3401:             if ($$last_resets{$part}) {  
1.270     albertel 3402:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3403: 					   $part);
                   3404:             }
1.269     raeburn  3405:             $result.='<input type="hidden" name="'.
                   3406:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3407:             $result.='<input type="hidden" name="'.
                   3408:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3409:             $aggregates{$part} = 1;
                   3410:         }
1.41      ng       3411: 	if ($type eq 'awarded') {
1.320     albertel 3412: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3413: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3414: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3415: 	    $result.='<input type="text" name="'.
1.89      albertel 3416: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3417: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3418: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3419: 	} elsif ($type eq 'solved') {
                   3420: 	    my ($status,$foo)=split(/_/,$score,2);
                   3421: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3422: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3423: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3424: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3425: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3426: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3427: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3428: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3429: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3430: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3431: 	} else {
                   3432: 	    $result.='<input type="hidden" name="'.
                   3433: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3434: 		    "\n";
1.233     albertel 3435: 	    $result.='<input type="text" name="'.
1.122     ng       3436: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3437: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3438: 	}
                   3439:     }
1.474     albertel 3440:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3441:     return $result;
1.38      ng       3442: }
                   3443: 
1.44      ng       3444: #--- change scores for all the students in a section/class
                   3445: #    record does not get update if unchanged
1.38      ng       3446: sub editgrades {
1.41      ng       3447:     my ($request) = @_;
                   3448: 
1.324     albertel 3449:     my $symb=&get_symb($request);
1.433     banghart 3450:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3451:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3452:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3453:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3454: 
1.477     albertel 3455:     my $result= &Apache::loncommon::start_data_table().
                   3456: 	&Apache::loncommon::start_data_table_header_row().
                   3457: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3458: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3459:     my %scoreptr = (
                   3460: 		    'correct'  =>'correct_by_override',
                   3461: 		    'incorrect'=>'incorrect_by_override',
                   3462: 		    'excused'  =>'excused',
                   3463: 		    'ungraded' =>'ungraded_attempted',
                   3464: 		    'nothing'  => '',
                   3465: 		    );
1.257     albertel 3466:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3467: 
1.44      ng       3468:     my (@partid);
                   3469:     my %weight = ();
1.54      albertel 3470:     my %columns = ();
1.44      ng       3471:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3472: 
1.324     albertel 3473:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3474:     my $header;
1.257     albertel 3475:     while ($ctr < $env{'form.totalparts'}) {
                   3476: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3477: 	push(@partid,$partid);
1.257     albertel 3478: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3479: 	$ctr++;
1.54      albertel 3480:     }
1.324     albertel 3481:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3482:     foreach my $partid (@partid) {
1.478     albertel 3483: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3484: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3485: 	$columns{$partid}=2;
                   3486: 	foreach my $stores (@parts) {
                   3487: 	    my ($part,$type) = &split_part_type($stores);
                   3488: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3489: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3490: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3491: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3492:             my $narrowtext = &mt('Tries');
                   3493: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3494: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3495: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3496: 	    $columns{$partid}+=2;
                   3497: 	}
                   3498:     }
                   3499:     foreach my $partid (@partid) {
1.324     albertel 3500: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3501: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3502: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3503: 	    '</th>';
1.54      albertel 3504: 
1.44      ng       3505:     }
1.477     albertel 3506:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3507: 	&Apache::loncommon::start_data_table_header_row().
                   3508: 	$header.
                   3509: 	&Apache::loncommon::end_data_table_header_row();
                   3510:     my @noupdate;
1.126     ng       3511:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3512:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3513: 	my $line;
1.257     albertel 3514: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3515: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3516: 	my %newrecord;
                   3517: 	my $updateflag = 0;
1.281     albertel 3518: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3519: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3520: 	if (!&canmodify($usec)) {
1.126     ng       3521: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3522: 	    push(@noupdate,
1.478     albertel 3523: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3524: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3525: 	    next;
                   3526: 	}
1.269     raeburn  3527:         my %aggregate = ();
                   3528:         my $aggregateflag = 0;
1.281     albertel 3529: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3530: 	foreach (@partid) {
1.257     albertel 3531: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3532: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3533: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3534: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3535: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3536: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3537: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3538: 	    my $score;
                   3539: 	    if ($partial eq '') {
1.257     albertel 3540: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3541: 	    } elsif ($partial > 0) {
                   3542: 		$score = 'correct_by_override';
                   3543: 	    } elsif ($partial == 0) {
                   3544: 		$score = 'incorrect_by_override';
                   3545: 	    }
1.257     albertel 3546: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3547: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3548: 
1.292     albertel 3549: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3550: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3551: 	    if ($dropMenu eq 'reset status' &&
                   3552: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3553: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3554: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3555: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3556: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3557: 		$updateflag = 1;
1.269     raeburn  3558:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3559:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3560:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3561:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3562:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3563:                     $aggregateflag = 1;
                   3564:                 }
1.139     albertel 3565: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3566: 		$updateflag = 1;
                   3567: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3568: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3569: 		$rec_update++;
1.125     ng       3570: 	    }
                   3571: 
1.93      albertel 3572: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3573: 		'<td align="center">'.$awarded.
                   3574: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3575: 
1.54      albertel 3576: 
                   3577: 	    my $partid=$_;
                   3578: 	    foreach my $stores (@parts) {
                   3579: 		my ($part,$type) = &split_part_type($stores);
                   3580: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3581: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3582: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3583: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3584: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3585: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3586: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3587: 		    $updateflag=1;
                   3588: 		}
1.93      albertel 3589: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3590: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3591: 	    }
1.44      ng       3592: 	}
1.477     albertel 3593: 	$line.="\n";
1.301     albertel 3594: 
                   3595: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3596: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3597: 
1.44      ng       3598: 	if ($updateflag) {
                   3599: 	    $count++;
1.257     albertel 3600: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3601: 				    $udom,$uname);
1.301     albertel 3602: 
                   3603: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3604: 					      $cnum,$udom,$uname)) {
                   3605: 		# need to figure out if should be in queue.
                   3606: 		my %record =  
                   3607: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3608: 					     $udom,$uname);
                   3609: 		my $all_graded = 1;
                   3610: 		my $none_graded = 1;
                   3611: 		foreach my $part (@parts) {
                   3612: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3613: 			$all_graded = 0;
                   3614: 		    } else {
                   3615: 			$none_graded = 0;
                   3616: 		    }
                   3617: 		}
                   3618: 
                   3619: 		if ($all_graded || $none_graded) {
                   3620: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3621: 							   $symb,$cdom,$cnum,
                   3622: 							   $udom,$uname);
                   3623: 		}
                   3624: 	    }
                   3625: 
1.477     albertel 3626: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3627: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3628: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3629: 	    $updateCtr++;
1.93      albertel 3630: 	} else {
1.477     albertel 3631: 	    push(@noupdate,
                   3632: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3633: 	    $noupdateCtr++;
1.44      ng       3634: 	}
1.269     raeburn  3635:         if ($aggregateflag) {
                   3636:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3637: 				  $cdom,$cnum);
1.269     raeburn  3638:         }
1.93      albertel 3639:     }
1.477     albertel 3640:     if (@noupdate) {
1.126     ng       3641: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3642: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3643: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3644: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3645: 	    &mt('No Changes Occurred For the Students Below').
                   3646: 	    '</td>'.
1.477     albertel 3647: 	    &Apache::loncommon::end_data_table_row();
                   3648: 	foreach my $line (@noupdate) {
                   3649: 	    $result.=
                   3650: 		&Apache::loncommon::start_data_table_row().
                   3651: 		$line.
                   3652: 		&Apache::loncommon::end_data_table_row();
                   3653: 	}
1.44      ng       3654:     }
1.477     albertel 3655:     $result .= &Apache::loncommon::end_data_table().
                   3656: 	&show_grading_menu_form($symb);
1.478     albertel 3657:     my $msg = '<p><b>'.
                   3658: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3659: 	    $rec_update,$count).'</b><br />'.
                   3660: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3661: 	'</b></p>';
1.44      ng       3662:     return $title.$msg.$result;
1.5       albertel 3663: }
1.54      albertel 3664: 
                   3665: sub split_part_type {
                   3666:     my ($partstr) = @_;
                   3667:     my ($temp,@allparts)=split(/_/,$partstr);
                   3668:     my $type=pop(@allparts);
1.439     albertel 3669:     my $part=join('_',@allparts);
1.54      albertel 3670:     return ($part,$type);
                   3671: }
                   3672: 
1.44      ng       3673: #------------- end of section for handling grading by section/class ---------
                   3674: #
                   3675: #----------------------------------------------------------------------------
                   3676: 
1.5       albertel 3677: 
1.44      ng       3678: #----------------------------------------------------------------------------
                   3679: #
                   3680: #-------------------------- Next few routines handles grading by csv upload
                   3681: #
                   3682: #--- Javascript to handle csv upload
1.27      albertel 3683: sub csvupload_javascript_reverse_associate {
1.246     albertel 3684:     my $error1=&mt('You need to specify the username or ID');
                   3685:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3686:   return(<<ENDPICK);
                   3687:   function verify(vf) {
                   3688:     var foundsomething=0;
                   3689:     var founduname=0;
1.243     albertel 3690:     var foundID=0;
1.27      albertel 3691:     for (i=0;i<=vf.nfields.value;i++) {
                   3692:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3693:       if (i==0 && tw!=0) { foundID=1; }
                   3694:       if (i==1 && tw!=0) { founduname=1; }
                   3695:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3696:     }
1.246     albertel 3697:     if (founduname==0 && foundID==0) {
                   3698: 	alert('$error1');
                   3699: 	return;
1.27      albertel 3700:     }
                   3701:     if (foundsomething==0) {
1.246     albertel 3702: 	alert('$error2');
                   3703: 	return;
1.27      albertel 3704:     }
                   3705:     vf.submit();
                   3706:   }
                   3707:   function flip(vf,tf) {
                   3708:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3709:     var i;
                   3710:     for (i=0;i<=vf.nfields.value;i++) {
                   3711:       //can not pick the same destination field for both name and domain
                   3712:       if (((i ==0)||(i ==1)) && 
                   3713:           ((tf==0)||(tf==1)) && 
                   3714:           (i!=tf) &&
                   3715:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3716:         eval('vf.f'+i+'.selectedIndex=0;')
                   3717:       }
                   3718:     }
                   3719:   }
                   3720: ENDPICK
                   3721: }
                   3722: 
                   3723: sub csvupload_javascript_forward_associate {
1.246     albertel 3724:     my $error1=&mt('You need to specify the username or ID');
                   3725:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3726:   return(<<ENDPICK);
                   3727:   function verify(vf) {
                   3728:     var foundsomething=0;
                   3729:     var founduname=0;
1.243     albertel 3730:     var foundID=0;
1.27      albertel 3731:     for (i=0;i<=vf.nfields.value;i++) {
                   3732:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3733:       if (tw==1) { foundID=1; }
                   3734:       if (tw==2) { founduname=1; }
                   3735:       if (tw>3) { foundsomething=1; }
1.27      albertel 3736:     }
1.246     albertel 3737:     if (founduname==0 && foundID==0) {
                   3738: 	alert('$error1');
                   3739: 	return;
1.27      albertel 3740:     }
                   3741:     if (foundsomething==0) {
1.246     albertel 3742: 	alert('$error2');
                   3743: 	return;
1.27      albertel 3744:     }
                   3745:     vf.submit();
                   3746:   }
                   3747:   function flip(vf,tf) {
                   3748:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3749:     var i;
                   3750:     //can not pick the same destination field twice
                   3751:     for (i=0;i<=vf.nfields.value;i++) {
                   3752:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3753:         eval('vf.f'+i+'.selectedIndex=0;')
                   3754:       }
                   3755:     }
                   3756:   }
                   3757: ENDPICK
                   3758: }
                   3759: 
1.26      albertel 3760: sub csvuploadmap_header {
1.324     albertel 3761:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3762:     my $javascript;
1.257     albertel 3763:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3764: 	$javascript=&csvupload_javascript_reverse_associate();
                   3765:     } else {
                   3766: 	$javascript=&csvupload_javascript_forward_associate();
                   3767:     }
1.45      ng       3768: 
1.324     albertel 3769:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3770:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3771:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3772:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3773:     $request->print(<<ENDPICK);
1.26      albertel 3774: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3775: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3776: $result
1.326     albertel 3777: <hr />
1.26      albertel 3778: <h3>Identify fields</h3>
                   3779: Total number of records found in file: $distotal <hr />
                   3780: Enter as many fields as you can. The system will inform you and bring you back
                   3781: to this page if the data selected is insufficient to run your class.<hr />
                   3782: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3783: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3784: <input type="hidden" name="associate"  value="" />
                   3785: <input type="hidden" name="phase"      value="three" />
                   3786: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3787: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3788: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3789: <input type="hidden" name="upfile_associate" 
1.257     albertel 3790:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3791: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3792: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3793: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3794: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3795: <hr />
                   3796: <script type="text/javascript" language="Javascript">
                   3797: $javascript
                   3798: </script>
                   3799: ENDPICK
1.118     ng       3800:     return '';
1.26      albertel 3801: 
                   3802: }
                   3803: 
                   3804: sub csvupload_fields {
1.324     albertel 3805:     my ($symb) = @_;
                   3806:     my (@parts) = &getpartlist($symb);
1.556     weissno  3807:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3808: 		['username','Student Username'],
                   3809: 		['domain','Student Domain']);
1.324     albertel 3810:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3811:     foreach my $part (sort(@parts)) {
                   3812: 	my @datum;
                   3813: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3814: 	my $name=$part;
                   3815: 	if  (!$display) { $display = $name; }
                   3816: 	@datum=($name,$display);
1.244     albertel 3817: 	if ($name=~/^stores_(.*)_awarded/) {
                   3818: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3819: 	}
1.41      ng       3820: 	push(@fields,\@datum);
                   3821:     }
                   3822:     return (@fields);
1.26      albertel 3823: }
                   3824: 
                   3825: sub csvuploadmap_footer {
1.41      ng       3826:     my ($request,$i,$keyfields) =@_;
                   3827:     $request->print(<<ENDPICK);
1.26      albertel 3828: </table>
                   3829: <input type="hidden" name="nfields" value="$i" />
                   3830: <input type="hidden" name="keyfields" value="$keyfields" />
                   3831: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3832: </form>
                   3833: ENDPICK
                   3834: }
                   3835: 
1.283     albertel 3836: sub checkforfile_js {
1.539     riegler  3837:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       3838:     my $result =<<CSVFORMJS;
                   3839: <script type="text/javascript" language="javascript">
                   3840:     function checkUpload(formname) {
                   3841: 	if (formname.upfile.value == "") {
1.539     riegler  3842: 	    alert("$alertmsg");
1.86      ng       3843: 	    return false;
                   3844: 	}
                   3845: 	formname.submit();
                   3846:     }
                   3847:     </script>
                   3848: CSVFORMJS
1.283     albertel 3849:     return $result;
                   3850: }
                   3851: 
                   3852: sub upcsvScores_form {
                   3853:     my ($request) = shift;
1.324     albertel 3854:     my ($symb)=&get_symb($request);
1.283     albertel 3855:     if (!$symb) {return '';}
                   3856:     my $result=&checkforfile_js();
1.257     albertel 3857:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3858:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3859:     $result.=$table;
1.326     albertel 3860:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3861:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3862:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3863: 	'</b></td></tr>'."\n";
1.86      ng       3864:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3865:     my $upload=&mt("Upload Scores");
1.86      ng       3866:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3867:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3868:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3869:     $result.=<<ENDUPFORM;
1.106     albertel 3870: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3871: <input type="hidden" name="symb" value="$symb" />
                   3872: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3873: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3874: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3875: $upfile_select
1.370     www      3876: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3877: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3878: </form>
                   3879: ENDUPFORM
1.370     www      3880:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3881:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3882:     .'</td></tr></table>'."\n";
1.86      ng       3883:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3884:     $result.=&show_grading_menu_form($symb);
1.86      ng       3885:     return $result;
                   3886: }
                   3887: 
                   3888: 
1.26      albertel 3889: sub csvuploadmap {
1.41      ng       3890:     my ($request)= @_;
1.324     albertel 3891:     my ($symb)=&get_symb($request);
1.41      ng       3892:     if (!$symb) {return '';}
1.72      ng       3893: 
1.41      ng       3894:     my $datatoken;
1.257     albertel 3895:     if (!$env{'form.datatoken'}) {
1.41      ng       3896: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3897:     } else {
1.257     albertel 3898: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3899: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3900:     }
1.41      ng       3901:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3902:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3903:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3904:     my ($i,$keyfields);
                   3905:     if (@records) {
1.324     albertel 3906: 	my @fields=&csvupload_fields($symb);
1.45      ng       3907: 
1.257     albertel 3908: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3909: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3910: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3911: 							  \@fields);
                   3912: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3913: 	    chop($keyfields);
                   3914: 	} else {
                   3915: 	    unshift(@fields,['none','']);
                   3916: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3917: 							    \@fields);
1.311     banghart 3918:             foreach my $rec (@records) {
                   3919:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3920:                 if (%temp) {
                   3921:                     $keyfields=join(',',sort(keys(%temp)));
                   3922:                     last;
                   3923:                 }
                   3924:             }
1.41      ng       3925: 	}
                   3926:     }
                   3927:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3928:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3929: 
1.41      ng       3930:     return '';
1.27      albertel 3931: }
                   3932: 
1.246     albertel 3933: sub csvuploadoptions {
1.41      ng       3934:     my ($request)= @_;
1.324     albertel 3935:     my ($symb)=&get_symb($request);
1.257     albertel 3936:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3937:     my $ignore=&mt('Ignore First Line');
                   3938:     $request->print(<<ENDPICK);
                   3939: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3940: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3941: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3942: <!--
1.246     albertel 3943: <p>
                   3944: <label>
                   3945:    <input type="checkbox" name="show_full_results" />
                   3946:    Show a table of all changes
                   3947: </label>
                   3948: </p>
1.302     albertel 3949: -->
1.246     albertel 3950: <p>
                   3951: <label>
                   3952:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3953:    Overwrite any existing score
                   3954: </label>
                   3955: </p>
                   3956: ENDPICK
                   3957:     my %fields=&get_fields();
                   3958:     if (!defined($fields{'domain'})) {
1.257     albertel 3959: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3960: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3961:     }
1.257     albertel 3962:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3963: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3964: 	my $cleankey=$1;
                   3965: 	if ($cleankey eq 'command') { next; }
                   3966: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3967: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3968:     }
                   3969:     # FIXME do a check for any duplicated user ids...
                   3970:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3971:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3972: <hr /></form>'."\n");
1.324     albertel 3973:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3974:     return '';
                   3975: }
                   3976: 
                   3977: sub get_fields {
                   3978:     my %fields;
1.257     albertel 3979:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3980:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3981: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3982: 	    if ($env{'form.f'.$i} ne 'none') {
                   3983: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3984: 	    }
                   3985: 	} else {
1.257     albertel 3986: 	    if ($env{'form.f'.$i} ne 'none') {
                   3987: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3988: 	    }
                   3989: 	}
1.27      albertel 3990:     }
1.246     albertel 3991:     return %fields;
                   3992: }
                   3993: 
                   3994: sub csvuploadassign {
                   3995:     my ($request)= @_;
1.324     albertel 3996:     my ($symb)=&get_symb($request);
1.246     albertel 3997:     if (!$symb) {return '';}
1.345     bowersj2 3998:     my $error_msg = '';
1.246     albertel 3999:     &Apache::loncommon::load_tmp_file($request);
                   4000:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4001:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4002:     my %fields=&get_fields();
1.41      ng       4003:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4004:     my $courseid=$env{'request.course.id'};
1.97      albertel 4005:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4006:     my @notallowed;
1.41      ng       4007:     my @skipped;
                   4008:     my $countdone=0;
                   4009:     foreach my $grade (@gradedata) {
                   4010: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4011: 	my $domain;
                   4012: 	if ($entries{$fields{'domain'}}) {
                   4013: 	    $domain=$entries{$fields{'domain'}};
                   4014: 	} else {
1.257     albertel 4015: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4016: 	}
1.243     albertel 4017: 	$domain=~s/\s//g;
1.41      ng       4018: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4019: 	$username=~s/\s//g;
1.243     albertel 4020: 	if (!$username) {
                   4021: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4022: 	    $id=~s/\s//g;
1.243     albertel 4023: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4024: 	    $username=$ids{$id};
                   4025: 	}
1.41      ng       4026: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4027: 	    my $id=$entries{$fields{'ID'}};
                   4028: 	    $id=~s/\s//g;
                   4029: 	    if ($id) {
                   4030: 		push(@skipped,"$id:$domain");
                   4031: 	    } else {
                   4032: 		push(@skipped,"$username:$domain");
                   4033: 	    }
1.41      ng       4034: 	    next;
                   4035: 	}
1.108     albertel 4036: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4037: 	if (!&canmodify($usec)) {
                   4038: 	    push(@notallowed,"$username:$domain");
                   4039: 	    next;
                   4040: 	}
1.244     albertel 4041: 	my %points;
1.41      ng       4042: 	my %grades;
                   4043: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4044: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4045: 		$dest eq 'domain') { next; }
                   4046: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4047: 	    if ($dest=~/stores_(.*)_points/) {
                   4048: 		my $part=$1;
                   4049: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4050: 					      $symb,$domain,$username);
1.345     bowersj2 4051:                 if ($wgt) {
                   4052:                     $entries{$fields{$dest}}=~s/\s//g;
                   4053:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4054:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4055:                                           : 'correct_by_override';
1.345     bowersj2 4056:                     $grades{"resource.$part.awarded"}=$pcr;
                   4057:                     $grades{"resource.$part.solved"}=$award;
                   4058:                     $points{$part}=1;
                   4059:                 } else {
                   4060:                     $error_msg = "<br />" .
                   4061:                         &mt("Some point values were assigned"
                   4062:                             ." for problems with a weight "
                   4063:                             ."of zero. These values were "
                   4064:                             ."ignored.");
                   4065:                 }
1.244     albertel 4066: 	    } else {
                   4067: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4068: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4069: 		my $store_key=$dest;
                   4070: 		$store_key=~s/^stores/resource/;
                   4071: 		$store_key=~s/_/\./g;
                   4072: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4073: 	    }
1.41      ng       4074: 	}
1.508     www      4075: 	if (! %grades) { 
                   4076:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4077:         } else {
                   4078: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4079: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4080: 					   $env{'request.course.id'},
                   4081: 					   $domain,$username);
1.508     www      4082: 	   if ($result eq 'ok') {
                   4083: 	      $request->print('.');
                   4084: 	   } else {
                   4085: 	      $request->print("<p><span class=\"LC_error\">".
                   4086:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4087:                                   "$username:$domain",$result)."</span></p>");
                   4088: 	   }
                   4089: 	   $request->rflush();
                   4090: 	   $countdone++;
                   4091:         }
1.41      ng       4092:     }
1.570   ! www      4093:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4094:     if (@skipped) {
1.508     www      4095: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
1.106     albertel 4096: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4097:     }
                   4098:     if (@notallowed) {
1.508     www      4099: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
1.106     albertel 4100: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4101:     }
1.106     albertel 4102:     $request->print("<br />\n");
1.324     albertel 4103:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4104:     return $error_msg;
1.26      albertel 4105: }
1.44      ng       4106: #------------- end of section for handling csv file upload ---------
                   4107: #
                   4108: #-------------------------------------------------------------------
                   4109: #
1.122     ng       4110: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4111: #
                   4112: #--- Select a page/sequence and a student to grade
1.68      ng       4113: sub pickStudentPage {
                   4114:     my ($request) = shift;
                   4115: 
1.539     riegler  4116:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4117:     $request->print(<<LISTJAVASCRIPT);
                   4118: <script type="text/javascript" language="javascript">
                   4119: 
                   4120: function checkPickOne(formname) {
1.76      ng       4121:     if (radioSelection(formname.student) == null) {
1.539     riegler  4122: 	alert("$alertmsg");
1.68      ng       4123: 	return;
                   4124:     }
1.125     ng       4125:     ptr = pullDownSelection(formname.selectpage);
                   4126:     formname.page.value = formname["page"+ptr].value;
                   4127:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4128:     formname.submit();
                   4129: }
                   4130: 
                   4131: </script>
                   4132: LISTJAVASCRIPT
1.118     ng       4133:     &commonJSfunctions($request);
1.324     albertel 4134:     my ($symb) = &get_symb($request);
1.257     albertel 4135:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4136:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4137:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4138: 
1.398     albertel 4139:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4140: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4141: 
1.80      ng       4142:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4143:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4144:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4145: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4146: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4147:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4148:     my $ctr=0;
1.68      ng       4149:     foreach (@$titles) {
                   4150: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4151: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4152: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4153: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4154: 	$ctr++;
1.68      ng       4155:     }
1.485     albertel 4156:     $select.= '</select>';
1.539     riegler  4157:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4158: 
1.70      ng       4159:     $ctr=0;
                   4160:     foreach (@$titles) {
                   4161: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4162: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4163: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4164: 	$ctr++;
                   4165:     }
1.72      ng       4166:     $result.='<input type="hidden" name="page" />'."\n".
                   4167: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4168: 
1.485     albertel 4169:     my $options =
                   4170: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4171: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4172:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4173: 
                   4174:     $options =
                   4175: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4176: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4177: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4178:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4179:     
                   4180:     $result.=&build_section_inputs();
1.442     banghart 4181:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4182:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4183: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4184: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4185: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4186: 
1.539     riegler  4187:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4188: 
1.80      ng       4189:     $result.='&nbsp;<input type="button" '.
1.539     riegler  4190: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4191: 
1.68      ng       4192:     $request->print($result);
                   4193: 
1.485     albertel 4194:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4195: 	&Apache::loncommon::start_data_table().
                   4196: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4197: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4198: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4199: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4200: 	'<th>'.&nameUserString('header').'</th>'.
                   4201: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4202:  
1.76      ng       4203:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4204:     my $ptr = 1;
1.294     albertel 4205:     foreach my $student (sort 
                   4206: 			 {
                   4207: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4208: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4209: 			     }
                   4210: 			     return $a cmp $b;
                   4211: 			 } (keys(%$fullname))) {
1.68      ng       4212: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4213: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4214:                                   : '</td>');
1.126     ng       4215: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4216: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4217: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4218: 	$studentTable.=
                   4219: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4220:                          : '');
1.68      ng       4221: 	$ptr++;
                   4222:     }
1.484     albertel 4223:     if ($ptr%2 == 0) {
                   4224: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4225: 	    &Apache::loncommon::end_data_table_row();
                   4226:     }
                   4227:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4228:     $studentTable.='<input type="button" '.
1.539     riegler  4229: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4230: 
1.324     albertel 4231:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4232:     $request->print($studentTable);
                   4233: 
                   4234:     return '';
                   4235: }
                   4236: 
                   4237: sub getSymbMap {
1.132     bowersj2 4238:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4239: 
                   4240:     my %symbx = ();
                   4241:     my @titles = ();
1.117     bowersj2 4242:     my $minder = 0;
                   4243: 
                   4244:     # Gather every sequence that has problems.
1.240     albertel 4245:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4246: 					       1,0,1);
1.117     bowersj2 4247:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4248: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4249: 	    my $title = $minder.'.'.
                   4250: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4251: 	    push(@titles, $title); # minder in case two titles are identical
                   4252: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4253: 	    $minder++;
1.241     albertel 4254: 	}
1.68      ng       4255:     }
                   4256:     return \@titles,\%symbx;
                   4257: }
                   4258: 
1.72      ng       4259: #
                   4260: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4261: sub displayPage {
                   4262:     my ($request) = shift;
                   4263: 
1.324     albertel 4264:     my ($symb) = &get_symb($request);
1.257     albertel 4265:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4266:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4267:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4268:     my $pageTitle = $env{'form.page'};
1.103     albertel 4269:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4270:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4271:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4272: 
                   4273:     #need to make sure we have the correct data for later EXT calls, 
                   4274:     #thus invalidate the cache
                   4275:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4276:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4277:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4278:     &Apache::lonnet::clear_EXT_cache_status();
                   4279: 
1.103     albertel 4280:     if (!&canview($usec)) {
1.485     albertel 4281: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4282: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4283: 	return;
                   4284:     }
1.398     albertel 4285:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4286:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4287: 	'</h3>'."\n";
1.500     albertel 4288:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4289:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4290: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4291:     } else {
                   4292: 	delete($env{'form.CODE'});
                   4293:     }
1.71      ng       4294:     &sub_page_js($request);
                   4295:     $request->print($result);
                   4296: 
1.132     bowersj2 4297:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4298:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4299:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4300:     if (!$map) {
1.485     albertel 4301: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4302: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4303: 	return; 
                   4304:     }
1.68      ng       4305:     my $iterator = $navmap->getIterator($map->map_start(),
                   4306: 					$map->map_finish());
                   4307: 
1.71      ng       4308:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4309: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4310: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4311: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4312: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4313: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4314: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4315: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4316: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4317: 
1.382     albertel 4318:     if (defined($env{'form.CODE'})) {
                   4319: 	$studentTable.=
                   4320: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4321:     }
1.381     albertel 4322:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4323: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4324: 
1.485     albertel 4325:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4326: 	&Apache::loncommon::start_data_table().
                   4327: 	&Apache::loncommon::start_data_table_header_row().
                   4328: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4329: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4330: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4331: 
1.329     albertel 4332:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4333:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4334:     $iterator->next(); # skip the first BEGIN_MAP
                   4335:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4336:     while ($depth > 0) {
1.68      ng       4337:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4338:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4339: 
1.385     albertel 4340:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4341: 	    my $parts = $curRes->parts();
1.68      ng       4342:             my $title = $curRes->compTitle();
1.71      ng       4343: 	    my $symbx = $curRes->symb();
1.484     albertel 4344: 	    $studentTable.=
                   4345: 		&Apache::loncommon::start_data_table_row().
                   4346: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4347: 		(scalar(@{$parts}) == 1 ? '' 
                   4348: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4349: 							scalar(@{$parts}))
                   4350: 		 ).
                   4351: 		 '</td>';
1.71      ng       4352: 	    $studentTable.='<td valign="top">';
1.382     albertel 4353: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4354: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4355: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4356: 					     undef,'both',\%form);
1.71      ng       4357: 	    } else {
1.382     albertel 4358: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4359: 		$companswer =~ s|<form(.*?)>||g;
                   4360: 		$companswer =~ s|</form>||g;
1.71      ng       4361: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4362: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4363: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4364: #		}
1.116     ng       4365: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4366: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4367: 	    }
                   4368: 
1.257     albertel 4369: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4370: 
1.257     albertel 4371: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4372: 		if ($record{'version'} eq '') {
1.485     albertel 4373: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4374: 		} else {
1.116     ng       4375: 		    my %responseType = ();
                   4376: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4377: 			my @responseIds =$curRes->responseIds($partid);
                   4378: 			my @responseType =$curRes->responseType($partid);
                   4379: 			my %responseIds;
                   4380: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4381: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4382: 			}
                   4383: 			$responseType{$partid} = \%responseIds;
1.116     ng       4384: 		    }
1.148     albertel 4385: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4386: 
1.71      ng       4387: 		}
1.257     albertel 4388: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4389: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4390: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4391: 									$env{'request.course.id'},
1.71      ng       4392: 									'','.submission');
                   4393:  
                   4394: 	    }
1.103     albertel 4395: 	    if (&canmodify($usec)) {
                   4396: 		foreach my $partid (@{$parts}) {
                   4397: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4398: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4399: 		    $question++;
                   4400: 		}
1.196     albertel 4401: 		$prob++;
1.71      ng       4402: 	    }
                   4403: 	    $studentTable.='</td></tr>';
1.68      ng       4404: 
1.103     albertel 4405: 	}
1.68      ng       4406:         $curRes = $iterator->next();
                   4407:     }
                   4408: 
1.485     albertel 4409:     $studentTable.='</table>'."\n".
                   4410: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4411: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4412: 	'</form>'."\n";
1.324     albertel 4413:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4414:     $request->print($studentTable);
                   4415: 
                   4416:     return '';
1.119     ng       4417: }
                   4418: 
                   4419: sub displaySubByDates {
1.148     albertel 4420:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4421:     my $isCODE=0;
1.335     albertel 4422:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4423:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4424:     my $studentTable=&Apache::loncommon::start_data_table().
                   4425: 	&Apache::loncommon::start_data_table_header_row().
                   4426: 	'<th>'.&mt('Date/Time').'</th>'.
                   4427: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4428: 	'<th>'.&mt('Submission').'</th>'.
                   4429: 	'<th>'.&mt('Status').'</th>'.
                   4430: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4431:     my ($version);
                   4432:     my %mark;
1.148     albertel 4433:     my %orders;
1.119     ng       4434:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4435:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4436: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4437:     }
1.335     albertel 4438: 
                   4439:     my $interaction;
1.525     raeburn  4440:     my $no_increment = 1;
1.119     ng       4441:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4442: 	my $timestamp = 
                   4443: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4444: 	if (exists($$record{$version.':resource.0.version'})) {
                   4445: 	    $interaction = $$record{$version.':resource.0.version'};
                   4446: 	}
                   4447: 
                   4448: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4449: 		             : "$version:resource");
1.467     albertel 4450: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4451: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4452: 	if ($isCODE) {
                   4453: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4454: 	}
1.119     ng       4455: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4456: 	my @displaySub = ();
                   4457: 	foreach my $partid (@{$parts}) {
1.335     albertel 4458: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4459: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4460: 	    
                   4461: 
1.122     ng       4462: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4463: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4464: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4465: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4466: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4467: 
                   4468: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4469: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4470: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4471: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4472: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4473: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4474: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4475: 		    } else {
1.467     albertel 4476: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4477: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4478: 		    }
1.335     albertel 4479: 		    my $responseType=($isTask ? 'Task'
                   4480:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4481: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4482: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4483: 			$orders{$partid}->{$responseId}=
1.525     raeburn  4484: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
                   4485:                                        $no_increment);
1.148     albertel 4486: 		    }
1.147     albertel 4487: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4488: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4489: 		}
                   4490: 	    }
1.335     albertel 4491: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4492: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4493: 				    $$record{"$where.$partid.checkedin"},
                   4494: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4495: 					'<br />';
1.335     albertel 4496: 	    }
                   4497: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4498: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4499: 		    lc($$record{"$where.$partid.award"}).' '.
                   4500: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4501: 		    '<br />';
                   4502: 	    }
1.335     albertel 4503: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4504: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4505: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4506: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4507: 		$displaySub[2].=
                   4508: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4509: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4510: 	    }
                   4511: 	}
                   4512: 	# needed because old essay regrader has not parts info
                   4513: 	if (exists $$record{"$version:resource.regrader"}) {
                   4514: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4515: 	}
                   4516: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4517: 	if ($displaySub[2]) {
1.467     albertel 4518: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4519: 	}
1.467     albertel 4520: 	$studentTable.='&nbsp;</td>'.
                   4521: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4522:     }
1.467     albertel 4523:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4524:     return $studentTable;
1.71      ng       4525: }
                   4526: 
                   4527: sub updateGradeByPage {
                   4528:     my ($request) = shift;
                   4529: 
1.257     albertel 4530:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4531:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4532:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4533:     my $pageTitle = $env{'form.page'};
1.103     albertel 4534:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4535:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4536:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4537:     if (!&canmodify($usec)) {
1.526     raeburn  4538: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4539: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4540: 	return;
                   4541:     }
1.398     albertel 4542:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4543:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4544: 	'</h3>'."\n";
1.70      ng       4545: 
1.68      ng       4546:     $request->print($result);
                   4547: 
1.132     bowersj2 4548:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4549:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4550:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4551:     if (!$map) {
1.527     raeburn  4552: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4553: 	my ($symb)=&get_symb($request);
                   4554: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4555: 	return; 
                   4556:     }
1.71      ng       4557:     my $iterator = $navmap->getIterator($map->map_start(),
                   4558: 					$map->map_finish());
1.70      ng       4559: 
1.484     albertel 4560:     my $studentTable=
                   4561: 	&Apache::loncommon::start_data_table().
                   4562: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4563: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4564: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4565: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4566: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4567: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4568: 
                   4569:     $iterator->next(); # skip the first BEGIN_MAP
                   4570:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4571:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4572:     while ($depth > 0) {
1.71      ng       4573:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4574:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4575: 
1.385     albertel 4576:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4577: 	    my $parts = $curRes->parts();
1.71      ng       4578:             my $title = $curRes->compTitle();
                   4579: 	    my $symbx = $curRes->symb();
1.484     albertel 4580: 	    $studentTable.=
                   4581: 		&Apache::loncommon::start_data_table_row().
                   4582: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4583: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4584:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4585: 		.')').'</td>';
1.71      ng       4586: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4587: 
                   4588: 	    my %newrecord=();
                   4589: 	    my @displayPts=();
1.269     raeburn  4590:             my %aggregate = ();
                   4591:             my $aggregateflag = 0;
1.71      ng       4592: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4593: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4594: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4595: 
1.257     albertel 4596: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4597: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4598: 		my $partial = $newpts/$wgt;
                   4599: 		my $score;
                   4600: 		if ($partial > 0) {
                   4601: 		    $score = 'correct_by_override';
1.125     ng       4602: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4603: 		    $score = 'incorrect_by_override';
                   4604: 		}
1.257     albertel 4605: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4606: 		if ($dropMenu eq 'excused') {
1.71      ng       4607: 		    $partial = '';
                   4608: 		    $score = 'excused';
1.125     ng       4609: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4610: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4611: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4612: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4613: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4614: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4615: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4616: 		    $changeflag++;
                   4617: 		    $newpts = '';
1.269     raeburn  4618:                     
                   4619:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4620:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4621:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4622:                     if ($aggtries > 0) {
                   4623:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4624:                         $aggregateflag = 1;
                   4625:                     }
1.71      ng       4626: 		}
1.324     albertel 4627: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4628: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4629: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4630: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4631: 		    '&nbsp;<br />';
1.526     raeburn  4632: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4633: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4634: 		    '&nbsp;<br />';
1.71      ng       4635: 		$question++;
1.380     albertel 4636: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4637: 
1.71      ng       4638: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4639: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4640: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4641: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4642: 
                   4643: 		$changeflag++;
                   4644: 	    }
                   4645: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4646: 		my %record = 
                   4647: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4648: 					     $udom,$uname);
                   4649: 
                   4650: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4651: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4652: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4653: 		    $newrecord{'resource.CODE'} = '';
                   4654: 		}
1.257     albertel 4655: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4656: 					$udom,$uname);
1.382     albertel 4657: 		%record = &Apache::lonnet::restore($symbx,
                   4658: 						   $env{'request.course.id'},
                   4659: 						   $udom,$uname);
1.380     albertel 4660: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4661: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4662: 	    }
1.380     albertel 4663: 	    
1.269     raeburn  4664:             if ($aggregateflag) {
                   4665:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4666:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4667:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4668:             }
1.125     ng       4669: 
1.71      ng       4670: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4671: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4672: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4673: 
1.196     albertel 4674: 	    $prob++;
1.68      ng       4675: 	}
1.71      ng       4676:         $curRes = $iterator->next();
1.68      ng       4677:     }
1.98      albertel 4678: 
1.484     albertel 4679:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4680:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4681:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4682: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4683: 		  $changeflag));
1.76      ng       4684:     $request->print($grademsg.$studentTable);
1.68      ng       4685: 
1.70      ng       4686:     return '';
                   4687: }
                   4688: 
1.72      ng       4689: #-------- end of section for handling grading by page/sequence ---------
                   4690: #
                   4691: #-------------------------------------------------------------------
                   4692: 
1.75      albertel 4693: #--------------------Scantron Grading-----------------------------------
                   4694: #
                   4695: #------ start of section for handling grading by page/sequence ---------
                   4696: 
1.423     albertel 4697: =pod
                   4698: 
                   4699: =head1 Bubble sheet grading routines
                   4700: 
1.424     albertel 4701:   For this documentation:
                   4702: 
                   4703:    'scanline' refers to the full line of characters
                   4704:    from the file that we are parsing that represents one entire sheet
                   4705: 
                   4706:    'bubble line' refers to the data
                   4707:    representing the line of bubbles that are on the physical bubble sheet
                   4708: 
                   4709: 
                   4710: The overall process is that a scanned in bubble sheet data is uploaded
                   4711: into a course. When a user wants to grade, they select a
                   4712: sequence/folder of resources, a file of bubble sheet info, and pick
                   4713: one of the predefined configurations for what each scanline looks
                   4714: like.
                   4715: 
                   4716: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4717: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4718: because too light bubbling), 'double bubble' (each bubble line should
                   4719: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4720: invalid student/employee ID
1.424     albertel 4721: 
                   4722: If the CODE option is used that determines the randomization of the
1.556     weissno  4723: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4724: username:domain.
                   4725: 
                   4726: During the validation phase the instructor can choose to skip scanlines. 
                   4727: 
1.435     foxr     4728: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4729: 
                   4730:   scantron_original_filename (unmodified original file)
                   4731:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4732:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4733: 
                   4734: Also there is a separate hash nohist_scantrondata that contains extra
                   4735: correction information that isn't representable in the bubble sheet
                   4736: file (see &scantron_getfile() for more information)
                   4737: 
                   4738: After all scanlines are either valid, marked as valid or skipped, then
                   4739: foreach line foreach problem in the picked sequence, an ssi request is
                   4740: made that simulates a user submitting their selected letter(s) against
                   4741: the homework problem.
1.423     albertel 4742: 
                   4743: =over 4
                   4744: 
                   4745: 
                   4746: 
                   4747: =item defaultFormData
                   4748: 
                   4749:   Returns html hidden inputs used to hold context/default values.
                   4750: 
                   4751:  Arguments:
                   4752:   $symb - $symb of the current resource 
                   4753: 
                   4754: =cut
1.422     foxr     4755: 
1.81      albertel 4756: sub defaultFormData {
1.324     albertel 4757:     my ($symb)=@_;
1.447     foxr     4758:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4759:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4760:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4761: }
                   4762: 
1.447     foxr     4763: 
1.423     albertel 4764: =pod 
                   4765: 
                   4766: =item getSequenceDropDown
                   4767: 
                   4768:    Return html dropdown of possible sequences to grade
                   4769:  
                   4770:  Arguments:
                   4771:    $symb - $symb of the current resource 
                   4772: 
                   4773: =cut
1.422     foxr     4774: 
1.75      albertel 4775: sub getSequenceDropDown {
1.423     albertel 4776:     my ($symb)=@_;
1.75      albertel 4777:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4778:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4779:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4780:     my $ctr=0;
                   4781:     foreach (@$titles) {
                   4782: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4783: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4784: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4785: 	    '>'.$showtitle.'</option>'."\n";
                   4786: 	$ctr++;
                   4787:     }
                   4788:     $result.= '</select>';
                   4789:     return $result;
                   4790: }
                   4791: 
1.495     albertel 4792: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4793:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4794: 
                   4795: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4796: 
1.509     raeburn  4797: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4798:                                    # matchresponse or rankresponse, where 
                   4799:                                    # an individual response can have multiple 
                   4800:                                    # lines
1.503     raeburn  4801: 
                   4802: my %responsetype_per_response;     # responsetype for each response
                   4803: 
1.495     albertel 4804: # Save and restore the bubble lines array to the form env.
                   4805: 
                   4806: 
                   4807: sub save_bubble_lines {
                   4808:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4809: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4810: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4811: 	    $first_bubble_line{$line};
1.503     raeburn  4812:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4813:             $subdivided_bubble_lines{$line};
                   4814:         $env{"form.scantron.responsetype.$line"} =
                   4815:             $responsetype_per_response{$line};
1.495     albertel 4816:     }
                   4817: }
                   4818: 
                   4819: 
                   4820: sub restore_bubble_lines {
                   4821:     my $line = 0;
                   4822:     %bubble_lines_per_response = ();
                   4823:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4824: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4825: 	$bubble_lines_per_response{$line} = $value;
                   4826: 	$first_bubble_line{$line}  =
                   4827: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4828:         $subdivided_bubble_lines{$line} =
                   4829:             $env{"form.scantron.sub_bubblelines.$line"};
                   4830:         $responsetype_per_response{$line} =
                   4831:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4832: 	$line++;
                   4833:     }
                   4834: }
                   4835: 
                   4836: #  Given the parsed scanline, get the response for 
                   4837: #  'answer' number n:
                   4838: 
                   4839: sub get_response_bubbles {
                   4840:     my ($parsed_line, $response)  = @_;
                   4841: 
                   4842:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4843:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4844:     
                   4845:     my $selected = "";
                   4846: 
                   4847:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4848: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4849: 	$bubble_line++;
                   4850:     }
                   4851:     return $selected;
                   4852: }
1.423     albertel 4853: 
                   4854: =pod 
                   4855: 
                   4856: =item scantron_filenames
                   4857: 
                   4858:    Returns a list of the scantron files in the current course 
                   4859: 
                   4860: =cut
1.422     foxr     4861: 
1.202     albertel 4862: sub scantron_filenames {
1.257     albertel 4863:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4864:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4865:     my $getpropath = 1;
1.157     albertel 4866:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4867:                                        $getpropath);
1.202     albertel 4868:     my @possiblenames;
1.201     albertel 4869:     foreach my $filename (sort(@files)) {
1.157     albertel 4870: 	($filename)=split(/&/,$filename);
                   4871: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4872: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4873: 	push(@possiblenames,$filename);
                   4874:     }
                   4875:     return @possiblenames;
                   4876: }
                   4877: 
1.423     albertel 4878: =pod 
                   4879: 
                   4880: =item scantron_uploads
                   4881: 
                   4882:    Returns  html drop-down list of scantron files in current course.
                   4883: 
                   4884:  Arguments:
                   4885:    $file2grade - filename to set as selected in the dropdown
                   4886: 
                   4887: =cut
1.422     foxr     4888: 
1.202     albertel 4889: sub scantron_uploads {
1.209     ng       4890:     my ($file2grade) = @_;
1.202     albertel 4891:     my $result=	'<select name="scantron_selectfile">';
                   4892:     $result.="<option></option>";
                   4893:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4894: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4895:     }
                   4896:     $result.="</select>";
                   4897:     return $result;
                   4898: }
                   4899: 
1.423     albertel 4900: =pod 
                   4901: 
                   4902: =item scantron_scantab
                   4903: 
                   4904:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4905:   file.
                   4906: 
                   4907: =cut
1.422     foxr     4908: 
1.82      albertel 4909: sub scantron_scantab {
                   4910:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4911:     $result.='<option></option>'."\n";
1.518     raeburn  4912:     my @lines = &get_scantronformat_file();
                   4913:     if (@lines > 0) {
                   4914:         foreach my $line (@lines) {
                   4915:             next if (($line =~ /^\#/) || ($line eq ''));
                   4916: 	    my ($name,$descrip)=split(/:/,$line);
                   4917: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4918:         }
1.82      albertel 4919:     }
                   4920:     $result.='</select>'."\n";
1.518     raeburn  4921:     return $result;
                   4922: }
                   4923: 
                   4924: =pod
                   4925: 
                   4926: =item get_scantronformat_file
                   4927: 
                   4928:   Returns an array containing lines from the scantron format file for
                   4929:   the domain of the course.
                   4930: 
                   4931:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4932:   lines are from this file.
                   4933: 
                   4934:   Otherwise, if a default.tab has been published in RES space by the 
                   4935:   domainconfig user, lines are from this file.
                   4936: 
                   4937:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4938:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4939: 
1.518     raeburn  4940: =cut
                   4941: 
                   4942: sub get_scantronformat_file {
                   4943:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4944:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   4945:     my $gottab = 0;
                   4946:     my @lines;
                   4947:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4948:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4949:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4950:             if ($formatfile ne '-1') {
                   4951:                 @lines = split("\n",$formatfile,-1);
                   4952:                 $gottab = 1;
                   4953:             }
                   4954:         }
                   4955:     }
                   4956:     if (!$gottab) {
                   4957:         my $confname = $cdom.'-domainconfig';
                   4958:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4959:         my $formatfile =  &Apache::lonnet::getfile($default);
                   4960:         if ($formatfile ne '-1') {
                   4961:             @lines = split("\n",$formatfile,-1);
                   4962:             $gottab = 1;
                   4963:         }
                   4964:     }
                   4965:     if (!$gottab) {
1.519     raeburn  4966:         my @domains = &Apache::lonnet::current_machine_domains();
                   4967:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4968:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4969:             @lines = <$fh>;
                   4970:             close($fh);
                   4971:         } else {
                   4972:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   4973:             @lines = <$fh>;
                   4974:             close($fh);
                   4975:         }
1.518     raeburn  4976:     }
                   4977:     return @lines;
1.82      albertel 4978: }
                   4979: 
1.423     albertel 4980: =pod 
                   4981: 
                   4982: =item scantron_CODElist
                   4983: 
                   4984:   Returns html drop down of the saved CODE lists from current course,
                   4985:   generated from earlier printings.
                   4986: 
                   4987: =cut
1.422     foxr     4988: 
1.186     albertel 4989: sub scantron_CODElist {
1.257     albertel 4990:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4991:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4992:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4993:     my $namechoice='<option></option>';
1.225     albertel 4994:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4995: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4996: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4997: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4998:     }
                   4999:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5000:     return $namechoice;
                   5001: }
                   5002: 
1.423     albertel 5003: =pod 
                   5004: 
                   5005: =item scantron_CODEunique
                   5006: 
                   5007:   Returns the html for "Each CODE to be used once" radio.
                   5008: 
                   5009: =cut
1.422     foxr     5010: 
1.186     albertel 5011: sub scantron_CODEunique {
1.532     bisitz   5012:     my $result='<span class="LC_nobreak">
1.272     albertel 5013:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5014:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5015:                 </span>
1.532     bisitz   5016:                 <span class="LC_nobreak">
1.272     albertel 5017:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5018:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5019:                 </span>';
1.186     albertel 5020:     return $result;
                   5021: }
1.423     albertel 5022: 
                   5023: =pod 
                   5024: 
                   5025: =item scantron_selectphase
                   5026: 
                   5027:   Generates the initial screen to start the bubble sheet process.
                   5028:   Allows for - starting a grading run.
1.424     albertel 5029:              - downloading existing scan data (original, corrected
1.423     albertel 5030:                                                 or skipped info)
                   5031: 
                   5032:              - uploading new scan data
                   5033: 
                   5034:  Arguments:
                   5035:   $r          - The Apache request object
                   5036:   $file2grade - name of the file that contain the scanned data to score
                   5037: 
                   5038: =cut
1.186     albertel 5039: 
1.75      albertel 5040: sub scantron_selectphase {
1.209     ng       5041:     my ($r,$file2grade) = @_;
1.324     albertel 5042:     my ($symb)=&get_symb($r);
1.75      albertel 5043:     if (!$symb) {return '';}
1.423     albertel 5044:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 5045:     my $default_form_data=&defaultFormData($symb);
                   5046:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5047:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5048:     my $format_selector=&scantron_scantab();
1.186     albertel 5049:     my $CODE_selector=&scantron_CODElist();
                   5050:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5051:     my $result;
1.422     foxr     5052: 
1.513     foxr     5053:     $ssi_error = 0;
                   5054: 
1.422     foxr     5055:     # Chunk of form to prompt for a file to grade and how:
                   5056: 
1.489     albertel 5057:     $result.= '
                   5058:     <br />
                   5059:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5060:     <input type="hidden" name="command" value="scantron_warning" />
                   5061:     '.$default_form_data.'
                   5062:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5063:        '.&Apache::loncommon::start_data_table_header_row().'
                   5064:             <th colspan="2">
1.492     albertel 5065:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5066:             </th>
                   5067:        '.&Apache::loncommon::end_data_table_header_row().'
                   5068:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5069:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5070:        '.&Apache::loncommon::end_data_table_row().'
                   5071:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5072:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5073:        '.&Apache::loncommon::end_data_table_row().'
                   5074:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5075:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5076:        '.&Apache::loncommon::end_data_table_row().'
                   5077:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5078:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5079:        '.&Apache::loncommon::end_data_table_row().'
                   5080:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5081:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5082:        '.&Apache::loncommon::end_data_table_row().'
                   5083:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5084: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5085:             <td>
1.492     albertel 5086: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5087:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5088:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5089: 	    </td>
1.489     albertel 5090:        '.&Apache::loncommon::end_data_table_row().'
                   5091:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5092:             <td colspan="2">
1.492     albertel 5093:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
1.162     albertel 5094:             </td>
1.489     albertel 5095:        '.&Apache::loncommon::end_data_table_row().'
                   5096:     '.&Apache::loncommon::end_data_table().'
                   5097:     </form>
                   5098: ';
1.162     albertel 5099:    
                   5100:     $r->print($result);
                   5101: 
1.257     albertel 5102:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5103:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5104: 
1.422     foxr     5105: 	# Chunk of form to prompt for a scantron file upload.
                   5106: 
1.489     albertel 5107:         $r->print('
                   5108:     <br />
                   5109:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5110:        '.&Apache::loncommon::start_data_table_header_row().'
                   5111:             <th>
1.492     albertel 5112:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
1.489     albertel 5113:             </th>
                   5114:        '.&Apache::loncommon::end_data_table_header_row().'
                   5115:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5116:             <td>
1.489     albertel 5117: ');
1.324     albertel 5118:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5119:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5120:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5121:     $r->print('
1.174     albertel 5122:               <script type="text/javascript" language="javascript">
                   5123:     function checkUpload(formname) {
                   5124: 	if (formname.upfile.value == "") {
1.492     albertel 5125: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5126: 	    return false;
                   5127: 	}
                   5128: 	formname.submit();
                   5129:     }
                   5130:               </script>
                   5131: 
1.492     albertel 5132:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5133:                 '.$default_form_data.'
                   5134:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5135:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5136:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5137:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5138:                 <br />
1.492     albertel 5139:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.174     albertel 5140:               </form>
1.492     albertel 5141: ');
1.162     albertel 5142: 
1.489     albertel 5143:         $r->print('
1.162     albertel 5144:             </td>
1.489     albertel 5145:        '.&Apache::loncommon::end_data_table_row().'
                   5146:        '.&Apache::loncommon::end_data_table().'
                   5147: ');
1.162     albertel 5148:     }
1.422     foxr     5149: 
                   5150:     # Chunk of the form that prompts to view a scoring office file,
                   5151:     # corrected file, skipped records in a file.
                   5152: 
1.489     albertel 5153:     $r->print('
                   5154:    <br />
                   5155:    <form action="/adm/grades" name="scantron_download">
                   5156:      '.$default_form_data.'
                   5157:      <input type="hidden" name="command" value="scantron_download" />
                   5158:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5159:        '.&Apache::loncommon::start_data_table_header_row().'
                   5160:               <th>
1.492     albertel 5161:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5162:               </th>
                   5163:        '.&Apache::loncommon::end_data_table_header_row().'
                   5164:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5165:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5166:                 <br />
1.492     albertel 5167:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5168:        '.&Apache::loncommon::end_data_table_row().'
                   5169:      '.&Apache::loncommon::end_data_table().'
                   5170:    </form>
                   5171:    <br />
                   5172: ');
1.162     albertel 5173: 
1.457     banghart 5174:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5175: 
1.528     raeburn  5176:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5177:              $default_form_data."\n".
                   5178:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5179:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5180:              '<th colspan="2">
                   5181:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
                   5182:              '</th>'."\n".
                   5183:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5184:               &Apache::loncommon::start_data_table_row()."\n".
                   5185:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5186:               '<td> '.$sequence_selector.' </td>'.
                   5187:               &Apache::loncommon::end_data_table_row()."\n".
                   5188:               &Apache::loncommon::start_data_table_row()."\n".
                   5189:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5190:               '<td> '.$file_selector.' </td>'."\n".
                   5191:               &Apache::loncommon::end_data_table_row()."\n".
                   5192:               &Apache::loncommon::start_data_table_row()."\n".
                   5193:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5194:               '<td> '.$format_selector.' </td>'."\n".
                   5195:               &Apache::loncommon::end_data_table_row()."\n".
                   5196:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5197:               '<td> '.&mt('Options').' </td>'."\n".
                   5198:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5199:               &Apache::loncommon::end_data_table_row()."\n".
                   5200:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5201:               '<td colspan="2">'."\n".
                   5202:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
                   5203:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
                   5204:               '</td>'."\n".
                   5205:               &Apache::loncommon::end_data_table_row()."\n".
                   5206:               &Apache::loncommon::end_data_table()."\n".
                   5207:               '</form><br />');
1.457     banghart 5208:     $r->print($grading_menu_button);
1.523     raeburn  5209:     return;
1.75      albertel 5210: }
                   5211: 
1.423     albertel 5212: =pod
                   5213: 
                   5214: =item get_scantron_config
                   5215: 
                   5216:    Parse and return the scantron configuration line selected as a
                   5217:    hash of configuration file fields.
                   5218: 
                   5219:  Arguments:
                   5220:     which - the name of the configuration to parse from the file.
                   5221: 
                   5222: 
                   5223:  Returns:
                   5224:             If the named configuration is not in the file, an empty
                   5225:             hash is returned.
                   5226:     a hash with the fields
                   5227:       name         - internal name for the this configuration setup
                   5228:       description  - text to display to operator that describes this config
                   5229:       CODElocation - if 0 or the string 'none'
                   5230:                           - no CODE exists for this config
                   5231:                      if -1 || the string 'letter'
                   5232:                           - a CODE exists for this config and is
                   5233:                             a string of letters
                   5234:                      Unsupported value (but planned for future support)
                   5235:                           if a positive integer
                   5236:                                - The CODE exists as the first n items from
                   5237:                                  the question section of the form
                   5238:                           if the string 'number'
                   5239:                                - The CODE exists for this config and is
                   5240:                                  a string of numbers
                   5241:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5242:                      the CODE starts
                   5243:       CODElength  - length of the CODE
1.556     weissno  5244:       IDstart     - column where the student/employee ID number starts
                   5245:       IDlength    - length of the student/employee ID info
1.423     albertel 5246:       Qstart      - column where the information from the bubbled
                   5247:                     'questions' start
                   5248:       Qlength     - number of columns comprising a single bubble line from
                   5249:                     the sheet. (usually either 1 or 10)
1.424     albertel 5250:       Qon         - either a single character representing the character used
1.423     albertel 5251:                     to signal a bubble was chosen in the positional setup, or
                   5252:                     the string 'letter' if the letter of the chosen bubble is
                   5253:                     in the final, or 'number' if a number representing the
                   5254:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5255:       Qoff        - the character used to represent that a bubble was
                   5256:                     left blank
1.423     albertel 5257:       PaperID     - if the scanning process generates a unique number for each
                   5258:                     sheet scanned the column that this ID number starts in
                   5259:       PaperIDlength - number of columns that comprise the unique ID number
                   5260:                       for the sheet of paper
1.424     albertel 5261:       FirstName   - column that the first name starts in
1.423     albertel 5262:       FirstNameLength - number of columns that the first name spans
                   5263:  
                   5264:       LastName    - column that the last name starts in
                   5265:       LastNameLength - number of columns that the last name spans
                   5266: 
                   5267: =cut
1.422     foxr     5268: 
1.82      albertel 5269: sub get_scantron_config {
                   5270:     my ($which) = @_;
1.518     raeburn  5271:     my @lines = &get_scantronformat_file();
1.82      albertel 5272:     my %config;
1.157     albertel 5273:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5274:     foreach my $line (@lines) {
1.82      albertel 5275: 	my ($name,$descrip)=split(/:/,$line);
                   5276: 	if ($name ne $which ) { next; }
                   5277: 	chomp($line);
                   5278: 	my @config=split(/:/,$line);
                   5279: 	$config{'name'}=$config[0];
                   5280: 	$config{'description'}=$config[1];
                   5281: 	$config{'CODElocation'}=$config[2];
                   5282: 	$config{'CODEstart'}=$config[3];
                   5283: 	$config{'CODElength'}=$config[4];
                   5284: 	$config{'IDstart'}=$config[5];
                   5285: 	$config{'IDlength'}=$config[6];
                   5286: 	$config{'Qstart'}=$config[7];
1.497     foxr     5287:  	$config{'Qlength'}=$config[8];
1.82      albertel 5288: 	$config{'Qoff'}=$config[9];
                   5289: 	$config{'Qon'}=$config[10];
1.157     albertel 5290: 	$config{'PaperID'}=$config[11];
                   5291: 	$config{'PaperIDlength'}=$config[12];
                   5292: 	$config{'FirstName'}=$config[13];
                   5293: 	$config{'FirstNamelength'}=$config[14];
                   5294: 	$config{'LastName'}=$config[15];
                   5295: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5296: 	last;
                   5297:     }
                   5298:     return %config;
                   5299: }
                   5300: 
1.423     albertel 5301: =pod 
                   5302: 
                   5303: =item username_to_idmap
                   5304: 
1.556     weissno  5305:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5306:     student username:domain.
                   5307: 
                   5308:   Arguments:
                   5309: 
                   5310:     $classlist - reference to the class list hash. This is a hash
                   5311:                  keyed by student name:domain  whose elements are references
1.424     albertel 5312:                  to arrays containing various chunks of information
1.423     albertel 5313:                  about the student. (See loncoursedata for more info).
                   5314: 
                   5315:   Returns
                   5316:     %idmap - the constructed hash
                   5317: 
                   5318: =cut
                   5319: 
1.82      albertel 5320: sub username_to_idmap {
                   5321:     my ($classlist)= @_;
                   5322:     my %idmap;
                   5323:     foreach my $student (keys(%$classlist)) {
                   5324: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5325: 	    $student;
                   5326:     }
                   5327:     return %idmap;
                   5328: }
1.423     albertel 5329: 
                   5330: =pod
                   5331: 
1.424     albertel 5332: =item scantron_fixup_scanline
1.423     albertel 5333: 
                   5334:    Process a requested correction to a scanline.
                   5335: 
                   5336:   Arguments:
                   5337:     $scantron_config   - hash from &get_scantron_config()
                   5338:     $scan_data         - hash of correction information 
                   5339:                           (see &scantron_getfile())
                   5340:     $line              - existing scanline
                   5341:     $whichline         - line number of the passed in scanline
                   5342:     $field             - type of change to process 
                   5343:                          (either 
1.556     weissno  5344:                           'ID'     -> correct the student/employee ID number
1.423     albertel 5345:                           'CODE'   -> correct the CODE
                   5346:                           'answer' -> fixup the submitted answers)
                   5347:     
                   5348:    $args               - hash of additional info,
                   5349:                           - 'ID' 
                   5350:                                'newid' -> studentID to use in replacement
1.424     albertel 5351:                                           of existing one
1.423     albertel 5352:                           - 'CODE' 
                   5353:                                'CODE_ignore_dup' - set to true if duplicates
                   5354:                                                    should be ignored.
                   5355: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5356:                                         if the existing unfound code should
1.423     albertel 5357:                                         be used as is
                   5358:                           - 'answer'
                   5359:                                'response' - new answer or 'none' if blank
                   5360:                                'question' - the bubble line to change
1.503     raeburn  5361:                                'questionnum' - the question identifier,
                   5362:                                                may include subquestion. 
1.423     albertel 5363: 
                   5364:   Returns:
                   5365:     $line - the modified scanline
                   5366: 
                   5367:   Side effects: 
                   5368:     $scan_data - may be updated
                   5369: 
                   5370: =cut
                   5371: 
1.82      albertel 5372: 
1.157     albertel 5373: sub scantron_fixup_scanline {
                   5374:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5375:     if ($field eq 'ID') {
                   5376: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5377: 	    return ($line,1,'New value too large');
1.157     albertel 5378: 	}
                   5379: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5380: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5381: 				     $args->{'newid'});
                   5382: 	}
                   5383: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5384: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5385: 	if ($args->{'newid'}=~/^\s*$/) {
                   5386: 	    &scan_data($scan_data,"$whichline.user",
                   5387: 		       $args->{'username'}.':'.$args->{'domain'});
                   5388: 	}
1.186     albertel 5389:     } elsif ($field eq 'CODE') {
1.192     albertel 5390: 	if ($args->{'CODE_ignore_dup'}) {
                   5391: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5392: 	}
                   5393: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5394: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5395: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5396: 		return ($line,1,'New CODE value too large');
                   5397: 	    }
                   5398: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5399: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5400: 	    }
                   5401: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5402: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5403: 	}
1.157     albertel 5404:     } elsif ($field eq 'answer') {
1.497     foxr     5405: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5406: 	my $off=$scantron_config->{'Qoff'};
                   5407: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5408: 	my $answer=${off}x$length;
                   5409: 	if ($args->{'response'} eq 'none') {
                   5410: 	    &scan_data($scan_data,
1.503     raeburn  5411: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5412: 	} else {
                   5413: 	    if ($on eq 'letter') {
                   5414: 		my @alphabet=('A'..'Z');
                   5415: 		$answer=$alphabet[$args->{'response'}];
                   5416: 	    } elsif ($on eq 'number') {
                   5417: 		$answer=$args->{'response'}+1;
                   5418: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5419: 	    } else {
1.497     foxr     5420: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5421: 	    }
1.497     foxr     5422: 	    &scan_data($scan_data,
1.503     raeburn  5423: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5424: 	}
1.497     foxr     5425: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5426: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5427:     }
                   5428:     return $line;
                   5429: }
1.423     albertel 5430: 
                   5431: =pod
                   5432: 
                   5433: =item scan_data
                   5434: 
                   5435:     Edit or look up  an item in the scan_data hash.
                   5436: 
                   5437:   Arguments:
                   5438:     $scan_data  - The hash (see scantron_getfile)
                   5439:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5440:                   scantronfilename_key).
1.423     albertel 5441:     $data        - New value of the hash entry.
                   5442:     $delete      - If true, the entry is removed from the hash.
                   5443: 
                   5444:   Returns:
                   5445:     The new value of the hash table field (undefined if deleted).
                   5446: 
                   5447: =cut
                   5448: 
                   5449: 
1.157     albertel 5450: sub scan_data {
                   5451:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5452:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5453:     if (defined($value)) {
                   5454: 	$scan_data->{$filename.'_'.$key} = $value;
                   5455:     }
                   5456:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5457:     return $scan_data->{$filename.'_'.$key};
                   5458: }
1.423     albertel 5459: 
1.495     albertel 5460: # ----- These first few routines are general use routines.----
                   5461: 
                   5462: # Return the number of occurences of a pattern in a string.
                   5463: 
                   5464: sub occurence_count {
                   5465:     my ($string, $pattern) = @_;
                   5466: 
                   5467:     my @matches = ($string =~ /$pattern/g);
                   5468: 
                   5469:     return scalar(@matches);
                   5470: }
                   5471: 
                   5472: 
                   5473: # Take a string known to have digits and convert all the
                   5474: # digits into letters in the range J,A..I.
                   5475: 
                   5476: sub digits_to_letters {
                   5477:     my ($input) = @_;
                   5478: 
                   5479:     my @alphabet = ('J', 'A'..'I');
                   5480: 
                   5481:     my @input    = split(//, $input);
                   5482:     my $output ='';
                   5483:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5484: 	if ($input[$i] =~ /\d/) {
                   5485: 	    $output .= $alphabet[$input[$i]];
                   5486: 	} else {
                   5487: 	    $output .= $input[$i];
                   5488: 	}
                   5489:     }
                   5490:     return $output;
                   5491: }
                   5492: 
1.423     albertel 5493: =pod 
                   5494: 
                   5495: =item scantron_parse_scanline
                   5496: 
                   5497:   Decodes a scanline from the selected scantron file
                   5498: 
                   5499:  Arguments:
                   5500:     line             - The text of the scantron file line to process
                   5501:     whichline        - Line number
                   5502:     scantron_config  - Hash describing the format of the scantron lines.
                   5503:     scan_data        - Hash of extra information about the scanline
                   5504:                        (see scantron_getfile for more information)
                   5505:     just_header      - True if should not process question answers but only
                   5506:                        the stuff to the left of the answers.
                   5507:  Returns:
                   5508:    Hash containing the result of parsing the scanline
                   5509: 
                   5510:    Keys are all proceeded by the string 'scantron.'
                   5511: 
                   5512:        CODE    - the CODE in use for this scanline
                   5513:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5514:                  by the operator
                   5515:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5516:                             CODEs were selected, but the usage has been
                   5517:                             forced by the operator
1.556     weissno  5518:        ID  - student/employee ID
1.423     albertel 5519:        PaperID - if used, the ID number printed on the sheet when the 
                   5520:                  paper was scanned
                   5521:        FirstName - first name from the sheet
                   5522:        LastName  - last name from the sheet
                   5523: 
                   5524:      if just_header was not true these key may also exist
                   5525: 
1.447     foxr     5526:        missingerror - a list of bubble ranges that are considered to be answers
                   5527:                       to a single question that don't have any bubbles filled in.
                   5528:                       Of the form questionnumber:firstbubblenumber:count.
                   5529:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5530:                       to a single question that have more than one bubble filled in.
                   5531:                       Of the form questionnumber::firstbubblenumber:count
                   5532:    
                   5533:                 In the above, count is the number of bubble responses in the
                   5534:                 input line needed to represent the possible answers to the question.
                   5535:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5536:                 per line would have count = 2.
                   5537: 
1.423     albertel 5538:        maxquest     - the number of the last bubble line that was parsed
                   5539: 
                   5540:        (<number> starts at 1)
                   5541:        <number>.answer - zero or more letters representing the selected
                   5542:                          letters from the scanline for the bubble line 
                   5543:                          <number>.
                   5544:                          if blank there was either no bubble or there where
                   5545:                          multiple bubbles, (consult the keys missingerror and
                   5546:                          doubleerror if this is an error condition)
                   5547: 
                   5548: =cut
                   5549: 
1.82      albertel 5550: sub scantron_parse_scanline {
1.423     albertel 5551:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5552: 
1.82      albertel 5553:     my %record;
1.550     raeburn  5554:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5555:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5556:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5557:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5558: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5559: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5560: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5561: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5562: 	    $record{'scantron.CODE'}=substr($data,
                   5563: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5564: 					    $$scantron_config{'CODElength'});
1.191     albertel 5565: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5566: 		$record{'scantron.useCODE'}=1;
                   5567: 	    }
1.192     albertel 5568: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5569: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5570: 	    }
1.82      albertel 5571: 	} else {
                   5572: 	    #FIXME interpret first N questions
                   5573: 	}
                   5574:     }
1.83      albertel 5575:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5576: 				  $$scantron_config{'IDlength'});
1.157     albertel 5577:     $record{'scantron.PaperID'}=
                   5578: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5579: 	       $$scantron_config{'PaperIDlength'});
                   5580:     $record{'scantron.FirstName'}=
                   5581: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5582: 	       $$scantron_config{'FirstNamelength'});
                   5583:     $record{'scantron.LastName'}=
                   5584: 	substr($data,$$scantron_config{'LastName'}-1,
                   5585: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5586:     if ($just_header) { return \%record; }
1.194     albertel 5587: 
1.82      albertel 5588:     my @alphabet=('A'..'Z');
                   5589:     my $questnum=0;
1.447     foxr     5590:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5591: 
1.470     foxr     5592:     chomp($questions);		# Get rid of any trailing \n.
                   5593:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5594:     while (length($questions)) {
1.447     foxr     5595: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5596:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5597:                              || 1;
                   5598:         $questnum++;
                   5599:         my $quest_id = $questnum;
                   5600:         my $currentquest = substr($questions,0,$answer_length);
                   5601:         $questions       = substr($questions,$answer_length);
                   5602:         if (length($currentquest) < $answer_length) { next; }
                   5603: 
                   5604:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5605:             my $subquestnum = 1;
                   5606:             my $subquestions = $currentquest;
                   5607:             my @subanswers_needed = 
                   5608:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5609:             foreach my $subans (@subanswers_needed) {
                   5610:                 my $subans_length =
                   5611:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5612:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5613:                 $subquestions   = substr($subquestions,$subans_length);
                   5614:                 $quest_id = "$questnum.$subquestnum";
                   5615:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5616:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5617:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5618:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5619:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5620:                 } else {
                   5621:                     $ansnum = &scantron_validator_positional($ansnum,
                   5622:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5623:                 }
                   5624:                 $subquestnum ++;
                   5625:             }
                   5626:         } else {
                   5627:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5628:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5629:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5630:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5631:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5632:             } else {
                   5633:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5634:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5635:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5636:             }
                   5637:         }
                   5638:     }
                   5639:     $record{'scantron.maxquest'}=$questnum;
                   5640:     return \%record;
                   5641: }
1.447     foxr     5642: 
1.503     raeburn  5643: sub scantron_validator_lettnum {
                   5644:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5645:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5646: 
                   5647:     # Qon 'letter' implies for each slot in currquest we have:
                   5648:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5649:     #    about anything else (esp. a value of Qoff) for missing
                   5650:     #    bubbles.
                   5651:     #
                   5652:     # Qon 'number' implies each slot gives a digit that indexes the
                   5653:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5654:     #    and * or ? for double bubbles on a single line.
                   5655:     #
1.447     foxr     5656: 
1.503     raeburn  5657:     my $matchon;
                   5658:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5659:         $matchon = '[A-Z]';
                   5660:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5661:         $matchon = '\d';
                   5662:     }
                   5663:     my $occurrences = 0;
                   5664:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5665:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5666:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5667:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5668:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5669:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5670:         my @singlelines = split('',$currquest);
                   5671:         foreach my $entry (@singlelines) {
                   5672:             $occurrences = &occurence_count($entry,$matchon);
                   5673:             if ($occurrences > 1) {
                   5674:                 last;
                   5675:             }
                   5676:         } 
                   5677:     } else {
                   5678:         $occurrences = &occurence_count($currquest,$matchon); 
                   5679:     }
                   5680:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5681:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5682:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5683:             my $bubble = substr($currquest,$ans,1);
                   5684:             if ($bubble =~ /$matchon/ ) {
                   5685:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5686:                     if ($bubble == 0) {
                   5687:                         $bubble = 10; 
                   5688:                     }
                   5689:                     $record->{"scantron.$ansnum.answer"} = 
                   5690:                         $alphabet->[$bubble-1];
                   5691:                 } else {
                   5692:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5693:                 }
                   5694:             } else {
                   5695:                 $record->{"scantron.$ansnum.answer"}='';
                   5696:             }
                   5697:             $ansnum++;
                   5698:         }
                   5699:     } elsif (!defined($currquest)
                   5700:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5701:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5702:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5703:             $record->{"scantron.$ansnum.answer"}='';
                   5704:             $ansnum++;
                   5705:         }
                   5706:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5707:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5708:         }
                   5709:     } else {
                   5710:         if ($$scantron_config{'Qon'} eq 'number') {
                   5711:             $currquest = &digits_to_letters($currquest);            
                   5712:         }
                   5713:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5714:             my $bubble = substr($currquest,$ans,1);
                   5715:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5716:             $ansnum++;
                   5717:         }
                   5718:     }
                   5719:     return $ansnum;
                   5720: }
1.447     foxr     5721: 
1.503     raeburn  5722: sub scantron_validator_positional {
                   5723:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5724:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5725: 
1.503     raeburn  5726:     # Otherwise there's a positional notation;
                   5727:     # each bubble line requires Qlength items, and there are filled in
                   5728:     # bubbles for each case where there 'Qon' characters.
                   5729:     #
1.447     foxr     5730: 
1.503     raeburn  5731:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5732: 
1.503     raeburn  5733:     # If the split only gives us one element.. the full length of the
                   5734:     # answer string, no bubbles are filled in:
1.447     foxr     5735: 
1.507     raeburn  5736:     if ($answers_needed eq '') {
                   5737:         return;
                   5738:     }
                   5739: 
1.503     raeburn  5740:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5741:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5742:             $record->{"scantron.$ansnum.answer"}='';
                   5743:             $ansnum++;
                   5744:         }
                   5745:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5746:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5747:         }
                   5748:     } elsif (scalar(@array) == 2) {
                   5749:         my $location = length($array[0]);
                   5750:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5751:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5752:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5753:             if ($ans eq $line_num) {
                   5754:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5755:             } else {
                   5756:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5757:             }
                   5758:             $ansnum++;
                   5759:          }
                   5760:     } else {
                   5761:         #  If there's more than one instance of a bubble character
                   5762:         #  That's a double bubble; with positional notation we can
                   5763:         #  record all the bubbles filled in as well as the
                   5764:         #  fact this response consists of multiple bubbles.
                   5765:         #
                   5766:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5767:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5768:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5769:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5770:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5771:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5772:             my $doubleerror = 0;
                   5773:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5774:                    (!$doubleerror)) {
                   5775:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5776:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5777:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5778:                if (length(@currarray) > 2) {
                   5779:                    $doubleerror = 1;
                   5780:                } 
                   5781:             }
                   5782:             if ($doubleerror) {
                   5783:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5784:             }
                   5785:         } else {
                   5786:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5787:         }
                   5788:         my $item = $ansnum;
                   5789:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5790:             $record->{"scantron.$item.answer"} = '';
                   5791:             $item ++;
                   5792:         }
1.447     foxr     5793: 
1.503     raeburn  5794:         my @ans=@array;
                   5795:         my $i=0;
                   5796:         my $increment = 0;
                   5797:         while ($#ans) {
                   5798:             $i+=length($ans[0]) + $increment;
                   5799:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5800:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5801:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5802:             shift(@ans);
                   5803:             $increment = 1;
                   5804:         }
                   5805:         $ansnum += $answers_needed;
1.82      albertel 5806:     }
1.503     raeburn  5807:     return $ansnum;
1.82      albertel 5808: }
                   5809: 
1.423     albertel 5810: =pod
                   5811: 
                   5812: =item scantron_add_delay
                   5813: 
                   5814:    Adds an error message that occurred during the grading phase to a
                   5815:    queue of messages to be shown after grading pass is complete
                   5816: 
                   5817:  Arguments:
1.424     albertel 5818:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5819:    $scanline    - the scanline that caused the error
                   5820:    $errormesage - the error message
                   5821:    $errorcode   - a numeric code for the error
                   5822: 
                   5823:  Side Effects:
1.424     albertel 5824:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5825: 
                   5826: =cut
                   5827: 
1.82      albertel 5828: sub scantron_add_delay {
1.140     albertel 5829:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5830:     push(@$delayqueue,
                   5831: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5832: 	  'ecode' => $errorcode }
                   5833: 	 );
1.82      albertel 5834: }
                   5835: 
1.423     albertel 5836: =pod
                   5837: 
                   5838: =item scantron_find_student
                   5839: 
1.424     albertel 5840:    Finds the username for the current scanline
                   5841: 
                   5842:   Arguments:
                   5843:    $scantron_record - hash result from scantron_parse_scanline
                   5844:    $scan_data       - hash of correction information 
                   5845:                       (see &scantron_getfile() form more information)
                   5846:    $idmap           - hash from &username_to_idmap()
                   5847:    $line            - number of current scanline
                   5848:  
                   5849:   Returns:
                   5850:    Either 'username:domain' or undef if unknown
                   5851: 
1.423     albertel 5852: =cut
                   5853: 
1.82      albertel 5854: sub scantron_find_student {
1.157     albertel 5855:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5856:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5857:     if ($scanID =~ /^\s*$/) {
                   5858:  	return &scan_data($scan_data,"$line.user");
                   5859:     }
1.83      albertel 5860:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5861:  	if (lc($id) eq lc($scanID)) {
                   5862:  	    return $$idmap{$id};
                   5863:  	}
1.83      albertel 5864:     }
                   5865:     return undef;
                   5866: }
                   5867: 
1.423     albertel 5868: =pod
                   5869: 
                   5870: =item scantron_filter
                   5871: 
1.424     albertel 5872:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5873:    hidden resources was selected
                   5874: 
1.423     albertel 5875: =cut
                   5876: 
1.83      albertel 5877: sub scantron_filter {
                   5878:     my ($curres)=@_;
1.331     albertel 5879: 
                   5880:     if (ref($curres) && $curres->is_problem()) {
                   5881: 	# if the user has asked to not have either hidden
                   5882: 	# or 'randomout' controlled resources to be graded
                   5883: 	# don't include them
                   5884: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5885: 	    && $curres->randomout) {
                   5886: 	    return 0;
                   5887: 	}
1.83      albertel 5888: 	return 1;
                   5889:     }
                   5890:     return 0;
1.82      albertel 5891: }
                   5892: 
1.423     albertel 5893: =pod
                   5894: 
                   5895: =item scantron_process_corrections
                   5896: 
1.424     albertel 5897:    Gets correction information out of submitted form data and corrects
                   5898:    the scanline
                   5899: 
1.423     albertel 5900: =cut
                   5901: 
1.157     albertel 5902: sub scantron_process_corrections {
                   5903:     my ($r) = @_;
1.257     albertel 5904:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5905:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5906:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5907:     my $which=$env{'form.scantron_line'};
1.200     albertel 5908:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5909:     my ($skip,$err,$errmsg);
1.257     albertel 5910:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5911: 	$skip=1;
1.257     albertel 5912:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5913: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5914: 	    $env{'form.scantron_domain'};
1.157     albertel 5915: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5916: 	($line,$err,$errmsg)=
                   5917: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5918: 				     'ID',{'newid'=>$newid,
1.257     albertel 5919: 				    'username'=>$env{'form.scantron_username'},
                   5920: 				    'domain'=>$env{'form.scantron_domain'}});
                   5921:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5922: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5923: 	my $newCODE;
1.192     albertel 5924: 	my %args;
1.190     albertel 5925: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5926: 	    $newCODE='use_unfound';
1.190     albertel 5927: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5928: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5929: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5930: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5931: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5932: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5933: 	}
1.257     albertel 5934: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5935: 	    $args{'CODE_ignore_dup'}=1;
                   5936: 	}
                   5937: 	$args{'CODE'}=$newCODE;
1.186     albertel 5938: 	($line,$err,$errmsg)=
                   5939: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5940: 				     'CODE',\%args);
1.257     albertel 5941:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5942: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5943: 	    ($line,$err,$errmsg)=
                   5944: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5945: 					 $which,'answer',
                   5946: 					 { 'question'=>$question,
1.503     raeburn  5947: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   5948:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 5949: 	    if ($err) { last; }
                   5950: 	}
                   5951:     }
                   5952:     if ($err) {
1.398     albertel 5953: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5954:     } else {
1.200     albertel 5955: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5956: 	&scantron_putfile($scanlines,$scan_data);
                   5957:     }
                   5958: }
                   5959: 
1.423     albertel 5960: =pod
                   5961: 
                   5962: =item reset_skipping_status
                   5963: 
1.424     albertel 5964:    Forgets the current set of remember skipped scanlines (and thus
                   5965:    reverts back to considering all lines in the
                   5966:    scantron_skipped_<filename> file)
                   5967: 
1.423     albertel 5968: =cut
                   5969: 
1.200     albertel 5970: sub reset_skipping_status {
                   5971:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5972:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5973:     &scantron_putfile(undef,$scan_data);
                   5974: }
                   5975: 
1.423     albertel 5976: =pod
                   5977: 
                   5978: =item start_skipping
                   5979: 
1.424     albertel 5980:    Marks a scanline to be skipped. 
                   5981: 
1.423     albertel 5982: =cut
                   5983: 
1.376     albertel 5984: sub start_skipping {
1.200     albertel 5985:     my ($scan_data,$i)=@_;
                   5986:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5987:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5988: 	$remembered{$i}=2;
                   5989:     } else {
                   5990: 	$remembered{$i}=1;
                   5991:     }
1.200     albertel 5992:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5993: }
                   5994: 
1.423     albertel 5995: =pod
                   5996: 
                   5997: =item should_be_skipped
                   5998: 
1.424     albertel 5999:    Checks whether a scanline should be skipped.
                   6000: 
1.423     albertel 6001: =cut
                   6002: 
1.200     albertel 6003: sub should_be_skipped {
1.376     albertel 6004:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6005:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6006: 	# not redoing old skips
1.376     albertel 6007: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6008: 	return 0;
                   6009:     }
                   6010:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6011: 
                   6012:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6013: 	return 0;
                   6014:     }
1.200     albertel 6015:     return 1;
                   6016: }
                   6017: 
1.423     albertel 6018: =pod
                   6019: 
                   6020: =item remember_current_skipped
                   6021: 
1.424     albertel 6022:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6023:    file and remembers them into scan_data for later use.
                   6024: 
1.423     albertel 6025: =cut
                   6026: 
1.200     albertel 6027: sub remember_current_skipped {
                   6028:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6029:     my %to_remember;
                   6030:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6031: 	if ($scanlines->{'skipped'}[$i]) {
                   6032: 	    $to_remember{$i}=1;
                   6033: 	}
                   6034:     }
1.376     albertel 6035: 
1.200     albertel 6036:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6037:     &scantron_putfile(undef,$scan_data);
                   6038: }
                   6039: 
1.423     albertel 6040: =pod
                   6041: 
                   6042: =item check_for_error
                   6043: 
1.424     albertel 6044:     Checks if there was an error when attempting to remove a specific
                   6045:     scantron_.. bubble sheet data file. Prints out an error if
                   6046:     something went wrong.
                   6047: 
1.423     albertel 6048: =cut
                   6049: 
1.200     albertel 6050: sub check_for_error {
                   6051:     my ($r,$result)=@_;
                   6052:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6053: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6054:     }
                   6055: }
1.157     albertel 6056: 
1.423     albertel 6057: =pod
                   6058: 
                   6059: =item scantron_warning_screen
                   6060: 
1.424     albertel 6061:    Interstitial screen to make sure the operator has selected the
                   6062:    correct options before we start the validation phase.
                   6063: 
1.423     albertel 6064: =cut
                   6065: 
1.203     albertel 6066: sub scantron_warning_screen {
                   6067:     my ($button_text)=@_;
1.257     albertel 6068:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6069:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6070:     my $CODElist;
1.284     albertel 6071:     if ($scantron_config{'CODElocation'} &&
                   6072: 	$scantron_config{'CODEstart'} &&
                   6073: 	$scantron_config{'CODElength'}) {
                   6074: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6075: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6076: 	$CODElist=
1.492     albertel 6077: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6078: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6079:     }
1.492     albertel 6080:     return ('
1.203     albertel 6081: <p>
1.492     albertel 6082: <span class="LC_warning">
                   6083: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6084: </p>
                   6085: <table>
1.492     albertel 6086: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6087: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6088: '.$CODElist.'
1.203     albertel 6089: </table>
                   6090: <br />
1.492     albertel 6091: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6092: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6093: 
                   6094: <br />
1.492     albertel 6095: ');
1.203     albertel 6096: }
                   6097: 
1.423     albertel 6098: =pod
                   6099: 
                   6100: =item scantron_do_warning
                   6101: 
1.424     albertel 6102:    Check if the operator has picked something for all required
                   6103:    fields. Error out if something is missing.
                   6104: 
1.423     albertel 6105: =cut
                   6106: 
1.203     albertel 6107: sub scantron_do_warning {
                   6108:     my ($r)=@_;
1.324     albertel 6109:     my ($symb)=&get_symb($r);
1.203     albertel 6110:     if (!$symb) {return '';}
1.324     albertel 6111:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6112:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6113:     if ( $env{'form.selectpage'} eq '' ||
                   6114: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6115: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6116: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6117: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6118: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6119: 	} 
1.257     albertel 6120: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6121: 	    $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 6122: 	} 
1.257     albertel 6123: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6124: 	    $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 6125: 	} 
                   6126:     } else {
1.265     www      6127: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6128: 	$r->print('
                   6129: '.$warning.'
                   6130: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6131: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6132: ');
1.237     albertel 6133:     }
1.352     albertel 6134:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6135:     return '';
                   6136: }
                   6137: 
1.423     albertel 6138: =pod
                   6139: 
                   6140: =item scantron_form_start
                   6141: 
1.424     albertel 6142:     html hidden input for remembering all selected grading options
                   6143: 
1.423     albertel 6144: =cut
                   6145: 
1.203     albertel 6146: sub scantron_form_start {
                   6147:     my ($max_bubble)=@_;
                   6148:     my $result= <<SCANTRONFORM;
                   6149: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6150:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6151:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6152:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6153:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6154:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6155:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6156:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6157:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6158:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6159: SCANTRONFORM
1.447     foxr     6160: 
                   6161:   my $line = 0;
                   6162:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6163:        my $chunk =
                   6164: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6165:        $chunk .=
                   6166: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6167:        $chunk .= 
                   6168:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6169:        $chunk .=
                   6170:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6171:        $result .= $chunk;
                   6172:        $line++;
                   6173:    }
1.203     albertel 6174:     return $result;
                   6175: }
                   6176: 
1.423     albertel 6177: =pod
                   6178: 
                   6179: =item scantron_validate_file
                   6180: 
1.424     albertel 6181:     Dispatch routine for doing validation of a bubble sheet data file.
                   6182: 
                   6183:     Also processes any necessary information resets that need to
                   6184:     occur before validation begins (ignore previous corrections,
                   6185:     restarting the skipped records processing)
                   6186: 
1.423     albertel 6187: =cut
                   6188: 
1.157     albertel 6189: sub scantron_validate_file {
                   6190:     my ($r) = @_;
1.324     albertel 6191:     my ($symb)=&get_symb($r);
1.157     albertel 6192:     if (!$symb) {return '';}
1.324     albertel 6193:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6194:     
                   6195:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6196:     # them when doing the corrections reset
1.257     albertel 6197:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6198: 	&reset_skipping_status();
                   6199:     }
1.257     albertel 6200:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6201: 	&remember_current_skipped();
1.257     albertel 6202: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6203:     }
                   6204: 
1.257     albertel 6205:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6206: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6207: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6208: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6209: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6210:     }
1.200     albertel 6211: 
1.257     albertel 6212:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6213: 	&scantron_process_corrections($r);
                   6214:     }
1.503     raeburn  6215:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6216:     #get the student pick code ready
                   6217:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 6218:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 6219:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6220:     $r->print($result);
                   6221:     
1.334     albertel 6222:     my @validate_phases=( 'sequence',
                   6223: 			  'ID',
1.157     albertel 6224: 			  'CODE',
                   6225: 			  'doublebubble',
                   6226: 			  'missingbubbles');
1.257     albertel 6227:     if (!$env{'form.validatepass'}) {
                   6228: 	$env{'form.validatepass'} = 0;
1.157     albertel 6229:     }
1.257     albertel 6230:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6231: 
1.448     foxr     6232: 
1.157     albertel 6233:     my $stop=0;
                   6234:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6235: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6236: 	$r->rflush();
                   6237: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6238: 	{
                   6239: 	    no strict 'refs';
                   6240: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6241: 	}
                   6242:     }
                   6243:     if (!$stop) {
1.203     albertel 6244: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6245: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6246:                   $warning.
                   6247:                   &mt('Perform verification for each student after storage of submissions?').
                   6248:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6249:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6250:                   ('&nbsp;'x3).'<label>'.
                   6251:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6252:                   '</label></span><br />'.
                   6253:                   &mt('Grading will take longer if you use verification.').'<br />'.
                   6254:                   &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
                   6255:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6256:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6257:     } else {
                   6258: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6259: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6260:     }
                   6261:     if ($stop) {
1.334     albertel 6262: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6263: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6264: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6265: 
1.492     albertel 6266: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6267: 	} else {
1.503     raeburn  6268:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6269: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6270:             } else {
1.539     riegler  6271:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6272:             }
1.492     albertel 6273: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6274: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6275: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6276: 	}
1.157     albertel 6277:     }
1.352     albertel 6278:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6279:     return '';
                   6280: }
                   6281: 
1.423     albertel 6282: 
                   6283: =pod
                   6284: 
                   6285: =item scantron_remove_file
                   6286: 
1.424     albertel 6287:    Removes the requested bubble sheet data file, makes sure that
                   6288:    scantron_original_<filename> is never removed
                   6289: 
                   6290: 
1.423     albertel 6291: =cut
                   6292: 
1.200     albertel 6293: sub scantron_remove_file {
1.192     albertel 6294:     my ($which)=@_;
1.257     albertel 6295:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6296:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6297:     my $file='scantron_';
1.200     albertel 6298:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6299: 	$file.=$which.'_';
1.192     albertel 6300:     } else {
                   6301: 	return 'refused';
                   6302:     }
1.257     albertel 6303:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6304:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6305: }
                   6306: 
1.423     albertel 6307: 
                   6308: =pod
                   6309: 
                   6310: =item scantron_remove_scan_data
                   6311: 
1.424     albertel 6312:    Removes all scan_data correction for the requested bubble sheet
                   6313:    data file.  (In the case that both the are doing skipped records we need
                   6314:    to remember the old skipped lines for the time being so that element
                   6315:    persists for a while.)
                   6316: 
1.423     albertel 6317: =cut
                   6318: 
1.200     albertel 6319: sub scantron_remove_scan_data {
1.257     albertel 6320:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6321:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6322:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6323:     my @todelete;
1.257     albertel 6324:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6325:     foreach my $key (@keys) {
                   6326: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6327: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6328: 		$key=~/remember_skipping/) {
                   6329: 		next;
                   6330: 	    }
1.192     albertel 6331: 	    push(@todelete,$key);
                   6332: 	}
                   6333:     }
1.200     albertel 6334:     my $result;
1.192     albertel 6335:     if (@todelete) {
1.491     albertel 6336: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6337: 				       \@todelete,$cdom,$cname);
                   6338:     } else {
                   6339: 	$result = 'ok';
1.192     albertel 6340:     }
                   6341:     return $result;
                   6342: }
                   6343: 
1.423     albertel 6344: 
                   6345: =pod
                   6346: 
                   6347: =item scantron_getfile
                   6348: 
1.424     albertel 6349:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6350:     the scan_data hash
                   6351:   
                   6352:   Arguments:
                   6353:     None
                   6354: 
                   6355:   Returns:
                   6356:     2 hash references
                   6357: 
                   6358:      - first one has 
                   6359:          orig      -
                   6360:          corrected -
                   6361:          skipped   -  each of which points to an array ref of the specified
                   6362:                       file broken up into individual lines
                   6363:          count     - number of scanlines
                   6364:  
                   6365:      - second is the scan_data hash possible keys are
1.425     albertel 6366:        ($number refers to scanline numbered $number and thus the key affects
                   6367:         only that scanline
                   6368:         $bubline refers to the specific bubble line element and the aspects
                   6369:         refers to that specific bubble line element)
                   6370: 
                   6371:        $number.user - username:domain to use
                   6372:        $number.CODE_ignore_dup 
                   6373:                     - ignore the duplicate CODE error 
                   6374:        $number.useCODE
                   6375:                     - use the CODE in the scanline as is
                   6376:        $number.no_bubble.$bubline
                   6377:                     - it is valid that there is no bubbled in bubble
                   6378:                       at $number $bubline
                   6379:        remember_skipping
                   6380:                     - a frozen hash containing keys of $number and values
                   6381:                       of either 
                   6382:                         1 - we are on a 'do skipped records pass' and plan
                   6383:                             on processing this line
                   6384:                         2 - we are on a 'do skipped records pass' and this
                   6385:                             scanline has been marked to skip yet again
1.424     albertel 6386: 
1.423     albertel 6387: =cut
                   6388: 
1.157     albertel 6389: sub scantron_getfile {
1.200     albertel 6390:     #FIXME really would prefer a scantron directory
1.257     albertel 6391:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6392:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6393:     my $lines;
                   6394:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6395: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6396:     my %scanlines;
                   6397:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6398:     my $temp=$scanlines{'orig'};
                   6399:     $scanlines{'count'}=$#$temp;
                   6400: 
                   6401:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6402: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6403:     if ($lines eq '-1') {
                   6404: 	$scanlines{'corrected'}=[];
                   6405:     } else {
                   6406: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6407:     }
                   6408:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6409: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6410:     if ($lines eq '-1') {
                   6411: 	$scanlines{'skipped'}=[];
                   6412:     } else {
                   6413: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6414:     }
1.175     albertel 6415:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6416:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6417:     my %scan_data = @tmp;
                   6418:     return (\%scanlines,\%scan_data);
                   6419: }
                   6420: 
1.423     albertel 6421: =pod
                   6422: 
                   6423: =item lonnet_putfile
                   6424: 
1.424     albertel 6425:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6426: 
                   6427:  Arguments:
                   6428:    $contents - data to store
                   6429:    $filename - filename to store $contents into
                   6430: 
                   6431:  Returns:
                   6432:    result value from &Apache::lonnet::finishuserfileupload
                   6433: 
1.423     albertel 6434: =cut
                   6435: 
1.157     albertel 6436: sub lonnet_putfile {
                   6437:     my ($contents,$filename)=@_;
1.257     albertel 6438:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6439:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6440:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6441:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6442: 
                   6443: }
                   6444: 
1.423     albertel 6445: =pod
                   6446: 
                   6447: =item scantron_putfile
                   6448: 
1.424     albertel 6449:     Stores the current version of the bubble sheet data files, and the
                   6450:     scan_data hash. (Does not modify the original version only the
                   6451:     corrected and skipped versions.
                   6452: 
                   6453:  Arguments:
                   6454:     $scanlines - hash ref that looks like the first return value from
                   6455:                  &scantron_getfile()
                   6456:     $scan_data - hash ref that looks like the second return value from
                   6457:                  &scantron_getfile()
                   6458: 
1.423     albertel 6459: =cut
                   6460: 
1.157     albertel 6461: sub scantron_putfile {
                   6462:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6463:     #FIXME really would prefer a scantron directory
1.257     albertel 6464:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6465:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6466:     if ($scanlines) {
                   6467: 	my $prefix='scantron_';
1.157     albertel 6468: # no need to update orig, shouldn't change
                   6469: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6470: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6471: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6472: 			$prefix.'corrected_'.
1.257     albertel 6473: 			$env{'form.scantron_selectfile'});
1.200     albertel 6474: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6475: 			$prefix.'skipped_'.
1.257     albertel 6476: 			$env{'form.scantron_selectfile'});
1.200     albertel 6477:     }
1.175     albertel 6478:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6479: }
                   6480: 
1.423     albertel 6481: =pod
                   6482: 
                   6483: =item scantron_get_line
                   6484: 
1.424     albertel 6485:    Returns the correct version of the scanline
                   6486: 
                   6487:  Arguments:
                   6488:     $scanlines - hash ref that looks like the first return value from
                   6489:                  &scantron_getfile()
                   6490:     $scan_data - hash ref that looks like the second return value from
                   6491:                  &scantron_getfile()
                   6492:     $i         - number of the requested line (starts at 0)
                   6493: 
                   6494:  Returns:
                   6495:    A scanline, (either the original or the corrected one if it
                   6496:    exists), or undef if the requested scanline should be
                   6497:    skipped. (Either because it's an skipped scanline, or it's an
                   6498:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6499:    pass.
                   6500: 
1.423     albertel 6501: =cut
                   6502: 
1.157     albertel 6503: sub scantron_get_line {
1.200     albertel 6504:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6505:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6506:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6507:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6508:     return $scanlines->{'orig'}[$i]; 
                   6509: }
                   6510: 
1.423     albertel 6511: =pod
                   6512: 
                   6513: =item scantron_todo_count
                   6514: 
1.424     albertel 6515:     Counts the number of scanlines that need processing.
                   6516: 
                   6517:  Arguments:
                   6518:     $scanlines - hash ref that looks like the first return value from
                   6519:                  &scantron_getfile()
                   6520:     $scan_data - hash ref that looks like the second return value from
                   6521:                  &scantron_getfile()
                   6522: 
                   6523:  Returns:
                   6524:     $count - number of scanlines to process
                   6525: 
1.423     albertel 6526: =cut
                   6527: 
1.200     albertel 6528: sub get_todo_count {
                   6529:     my ($scanlines,$scan_data)=@_;
                   6530:     my $count=0;
                   6531:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6532: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6533: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6534: 	$count++;
                   6535:     }
                   6536:     return $count;
                   6537: }
                   6538: 
1.423     albertel 6539: =pod
                   6540: 
                   6541: =item scantron_put_line
                   6542: 
1.424     albertel 6543:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6544:     data file.
                   6545: 
                   6546:  Arguments:
                   6547:     $scanlines - hash ref that looks like the first return value from
                   6548:                  &scantron_getfile()
                   6549:     $scan_data - hash ref that looks like the second return value from
                   6550:                  &scantron_getfile()
                   6551:     $i         - line number to update
                   6552:     $newline   - contents of the updated scanline
                   6553:     $skip      - if true make the line for skipping and update the
                   6554:                  'skipped' file
                   6555: 
1.423     albertel 6556: =cut
                   6557: 
1.157     albertel 6558: sub scantron_put_line {
1.200     albertel 6559:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6560:     if ($skip) {
                   6561: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6562: 	&start_skipping($scan_data,$i);
1.157     albertel 6563: 	return;
                   6564:     }
                   6565:     $scanlines->{'corrected'}[$i]=$newline;
                   6566: }
                   6567: 
1.423     albertel 6568: =pod
                   6569: 
                   6570: =item scantron_clear_skip
                   6571: 
1.424     albertel 6572:    Remove a line from the 'skipped' file
                   6573: 
                   6574:  Arguments:
                   6575:     $scanlines - hash ref that looks like the first return value from
                   6576:                  &scantron_getfile()
                   6577:     $scan_data - hash ref that looks like the second return value from
                   6578:                  &scantron_getfile()
                   6579:     $i         - line number to update
                   6580: 
1.423     albertel 6581: =cut
                   6582: 
1.376     albertel 6583: sub scantron_clear_skip {
                   6584:     my ($scanlines,$scan_data,$i)=@_;
                   6585:     if (exists($scanlines->{'skipped'}[$i])) {
                   6586: 	undef($scanlines->{'skipped'}[$i]);
                   6587: 	return 1;
                   6588:     }
                   6589:     return 0;
                   6590: }
                   6591: 
1.423     albertel 6592: =pod
                   6593: 
                   6594: =item scantron_filter_not_exam
                   6595: 
1.424     albertel 6596:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6597:    filter out resources that are not marked as 'exam' mode
                   6598: 
1.423     albertel 6599: =cut
                   6600: 
1.334     albertel 6601: sub scantron_filter_not_exam {
                   6602:     my ($curres)=@_;
                   6603:     
                   6604:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6605: 	# if the user has asked to not have either hidden
                   6606: 	# or 'randomout' controlled resources to be graded
                   6607: 	# don't include them
                   6608: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6609: 	    && $curres->randomout) {
                   6610: 	    return 0;
                   6611: 	}
                   6612: 	return 1;
                   6613:     }
                   6614:     return 0;
                   6615: }
                   6616: 
1.423     albertel 6617: =pod
                   6618: 
                   6619: =item scantron_validate_sequence
                   6620: 
1.424     albertel 6621:     Validates the selected sequence, checking for resource that are
                   6622:     not set to exam mode.
                   6623: 
1.423     albertel 6624: =cut
                   6625: 
1.334     albertel 6626: sub scantron_validate_sequence {
                   6627:     my ($r,$currentphase) = @_;
                   6628: 
                   6629:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6630:     my (undef,undef,$sequence)=
                   6631: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6632: 
                   6633:     my $map=$navmap->getResourceByUrl($sequence);
                   6634: 
                   6635:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6636:                                     value="ignore" />');
                   6637:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6638: 	my @resources=
                   6639: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6640: 	if (@resources) {
1.357     banghart 6641: 	    $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 6642: 	    return (1,$currentphase);
                   6643: 	}
                   6644:     }
                   6645: 
                   6646:     return (0,$currentphase+1);
                   6647: }
                   6648: 
1.423     albertel 6649: 
                   6650: 
1.157     albertel 6651: sub scantron_validate_ID {
                   6652:     my ($r,$currentphase) = @_;
                   6653:     
                   6654:     #get student info
                   6655:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6656:     my %idmap=&username_to_idmap($classlist);
                   6657: 
                   6658:     #get scantron line setup
1.257     albertel 6659:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6660:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6661:     
                   6662:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6663: 
                   6664:     my %found=('ids'=>{},'usernames'=>{});
                   6665:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6666: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6667: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6668: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6669: 						 $scan_data);
                   6670: 	my $id=$$scan_record{'scantron.ID'};
                   6671: 	my $found;
                   6672: 	foreach my $checkid (keys(%idmap)) {
                   6673: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6674: 	}
                   6675: 	if ($found) {
                   6676: 	    my $username=$idmap{$found};
                   6677: 	    if ($found{'ids'}{$found}) {
                   6678: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6679: 					 $line,'duplicateID',$found);
1.194     albertel 6680: 		return(1,$currentphase);
1.157     albertel 6681: 	    } elsif ($found{'usernames'}{$username}) {
                   6682: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6683: 					 $line,'duplicateID',$username);
1.194     albertel 6684: 		return(1,$currentphase);
1.157     albertel 6685: 	    }
1.186     albertel 6686: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6687: 	    $found{'ids'}{$found}++;
                   6688: 	    $found{'usernames'}{$username}++;
                   6689: 	} else {
                   6690: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6691: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6692: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6693: 		    &scantron_get_correction($r,$i,$scan_record,
                   6694: 					     \%scantron_config,
                   6695: 					     $line,'duplicateID',$username);
1.194     albertel 6696: 		    return(1,$currentphase);
1.157     albertel 6697: 		} elsif (!defined($username)) {
                   6698: 		    &scantron_get_correction($r,$i,$scan_record,
                   6699: 					     \%scantron_config,
                   6700: 					     $line,'incorrectID');
1.194     albertel 6701: 		    return(1,$currentphase);
1.157     albertel 6702: 		}
                   6703: 		$found{'usernames'}{$username}++;
                   6704: 	    } else {
                   6705: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6706: 					 $line,'incorrectID');
1.194     albertel 6707: 		return(1,$currentphase);
1.157     albertel 6708: 	    }
                   6709: 	}
                   6710:     }
                   6711: 
                   6712:     return (0,$currentphase+1);
                   6713: }
                   6714: 
1.423     albertel 6715: 
1.157     albertel 6716: sub scantron_get_correction {
                   6717:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6718: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6719: #to show both the current line and the previous one and allow skipping
                   6720: #the previous one or the current one
                   6721: 
1.333     albertel 6722:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6723: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6724: 			    " for PaperID <tt>[_1]</tt>",
                   6725: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6726:     } else {
1.492     albertel 6727: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6728: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6729: 			    $i,$line)."</p> \n");
                   6730:     }
                   6731:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6732: 			  "The name on the paper is [_2],[_3]",
                   6733: 			  $$scan_record{'scantron.ID'},
                   6734: 			  $$scan_record{'scantron.LastName'},
                   6735: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6736: 
1.157     albertel 6737:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6738:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6739:                            # Array populated for doublebubble or
                   6740:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6741:                            # to validate radio button checking   
                   6742: 
1.157     albertel 6743:     if ($error =~ /ID$/) {
1.186     albertel 6744: 	if ($error eq 'incorrectID') {
1.492     albertel 6745: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6746: 		      "</p>\n");
1.157     albertel 6747: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6748: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6749: 	}
1.242     albertel 6750: 	$r->print($message);
1.492     albertel 6751: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6752: 	$r->print("\n<ul><li> ");
                   6753: 	#FIXME it would be nice if this sent back the user ID and
                   6754: 	#could do partial userID matches
                   6755: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6756: 				       'scantron_username','scantron_domain'));
                   6757: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6758: 	$r->print("\n@".
1.257     albertel 6759: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6760: 
                   6761: 	$r->print('</li>');
1.186     albertel 6762:     } elsif ($error =~ /CODE$/) {
                   6763: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6764: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6765: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6766: 	    $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 6767: 	}
1.492     albertel 6768: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6769: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6770: 	$r->print($message);
1.492     albertel 6771: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6772: 	$r->print("\n<br /> ");
1.194     albertel 6773: 	my $i=0;
1.273     albertel 6774: 	if ($error eq 'incorrectCODE' 
                   6775: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6776: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6777: 	    if ($closest > 0) {
                   6778: 		foreach my $testcode (@{$closest}) {
                   6779: 		    my $checked='';
1.569     bisitz   6780: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6781: 		    $r->print("
                   6782:    <label>
1.569     bisitz   6783:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6784:        ".&mt("Use the similar CODE [_1] instead.",
                   6785: 	    "<b><tt>".$testcode."</tt></b>")."
                   6786:     </label>
                   6787:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6788: 		    $r->print("\n<br />");
                   6789: 		    $i++;
                   6790: 		}
1.194     albertel 6791: 	    }
                   6792: 	}
1.273     albertel 6793: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6794: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6795: 	    $r->print("
                   6796:     <label>
1.569     bisitz   6797:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6798:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6799: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6800:     </label>");
1.273     albertel 6801: 	    $r->print("\n<br />");
                   6802: 	}
1.194     albertel 6803: 
1.188     albertel 6804: 	$r->print(<<ENDSCRIPT);
                   6805: <script type="text/javascript">
                   6806: function change_radio(field) {
1.190     albertel 6807:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6808:     var i;
                   6809:     for (i=0;i<slct.length;i++) {
                   6810:         if (slct[i].value==field) { slct[i].checked=true; }
                   6811:     }
                   6812: }
                   6813: </script>
                   6814: ENDSCRIPT
1.187     albertel 6815: 	my $href="/adm/pickcode?".
1.359     www      6816: 	   "form=".&escape("scantronupload").
                   6817: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6818: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6819: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6820: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6821: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6822: 	    $r->print("
                   6823:     <label>
                   6824:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6825:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6826: 	     "<a target='_blank' href='$href'>","</a>")."
                   6827:     </label> 
1.558     bisitz   6828:     ".&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 6829: 	    $r->print("\n<br />");
                   6830: 	}
1.492     albertel 6831: 	$r->print("
                   6832:     <label>
                   6833:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6834:        ".&mt("Use [_1] as the CODE.",
                   6835: 	     "</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 6836: 	$r->print("\n<br /><br />");
1.157     albertel 6837:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6838: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6839: 
                   6840: 	# The form field scantron_questions is acutally a list of line numbers.
                   6841: 	# represented by this form so:
                   6842: 
                   6843: 	my $line_list = &questions_to_line_list($arg);
                   6844: 
1.157     albertel 6845: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6846: 		  $line_list.'" />');
1.242     albertel 6847: 	$r->print($message);
1.492     albertel 6848: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6849: 	foreach my $question (@{$arg}) {
1.503     raeburn  6850: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6851:                                                    $scan_record, $error);
1.524     raeburn  6852:             push(@lines_to_correct,@linenums);
1.157     albertel 6853: 	}
1.503     raeburn  6854:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6855:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6856: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6857: 	$r->print($message);
1.492     albertel 6858: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6859: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6860: 
1.503     raeburn  6861: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6862: 	# a list of question numbers. Therefore:
                   6863: 	#
                   6864: 	
                   6865: 	my $line_list = &questions_to_line_list($arg);
                   6866: 
1.157     albertel 6867: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6868: 		  $line_list.'" />');
1.157     albertel 6869: 	foreach my $question (@{$arg}) {
1.503     raeburn  6870: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6871:                                                    $scan_record, $error);
1.524     raeburn  6872:             push(@lines_to_correct,@linenums);
1.157     albertel 6873: 	}
1.503     raeburn  6874:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6875:     } else {
                   6876: 	$r->print("\n<ul>");
                   6877:     }
                   6878:     $r->print("\n</li></ul>");
1.497     foxr     6879: }
                   6880: 
1.503     raeburn  6881: sub verify_bubbles_checked {
                   6882:     my (@ansnums) = @_;
                   6883:     my $ansnumstr = join('","',@ansnums);
                   6884:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6885:     my $output = (<<ENDSCRIPT);
                   6886: <script type="text/javascript">
                   6887: function verify_bubble_radio(form) {
                   6888:     var ansnumArray = new Array ("$ansnumstr");
                   6889:     var need_bubble_count = 0;
                   6890:     for (var i=0; i<ansnumArray.length; i++) {
                   6891:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6892:             var bubble_picked = 0; 
                   6893:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6894:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6895:                     bubble_picked = 1;
                   6896:                 }
                   6897:             }
                   6898:             if (bubble_picked == 0) {
                   6899:                 need_bubble_count ++;
                   6900:             }
                   6901:         }
                   6902:     }
                   6903:     if (need_bubble_count) {
                   6904:         alert("$warning");
                   6905:         return;
                   6906:     }
                   6907:     form.submit(); 
                   6908: }
                   6909: </script>
                   6910: ENDSCRIPT
                   6911:     return $output;
                   6912: }
                   6913: 
1.497     foxr     6914: =pod
                   6915: 
                   6916: =item  questions_to_line_list
1.157     albertel 6917: 
1.497     foxr     6918: Converts a list of questions into a string of comma separated
                   6919: line numbers in the answer sheet used by the questions.  This is
                   6920: used to fill in the scantron_questions form field.
                   6921: 
                   6922:   Arguments:
                   6923:      questions    - Reference to an array of questions.
                   6924: 
                   6925: =cut
                   6926: 
                   6927: 
                   6928: sub questions_to_line_list {
                   6929:     my ($questions) = @_;
                   6930:     my @lines;
                   6931: 
1.503     raeburn  6932:     foreach my $item (@{$questions}) {
                   6933:         my $question = $item;
                   6934:         my ($first,$count,$last);
                   6935:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   6936:             $question = $1;
                   6937:             my $subquestion = $2;
                   6938:             $first = $first_bubble_line{$question-1} + 1;
                   6939:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6940:             my $subcount = 1;
                   6941:             while ($subcount<$subquestion) {
                   6942:                 $first += $subans[$subcount-1];
                   6943:                 $subcount ++;
                   6944:             }
                   6945:             $count = $subans[$subquestion-1];
                   6946:         } else {
                   6947: 	    $first   = $first_bubble_line{$question-1} + 1;
                   6948: 	    $count   = $bubble_lines_per_response{$question-1};
                   6949:         }
1.506     raeburn  6950:         $last = $first+$count-1;
1.503     raeburn  6951:         push(@lines, ($first..$last));
1.497     foxr     6952:     }
                   6953:     return join(',', @lines);
                   6954: }
                   6955: 
                   6956: =pod 
                   6957: 
                   6958: =item prompt_for_corrections
                   6959: 
                   6960: Prompts for a potentially multiline correction to the
                   6961: user's bubbling (factors out common code from scantron_get_correction
                   6962: for multi and missing bubble cases).
                   6963: 
                   6964:  Arguments:
                   6965:    $r           - Apache request object.
                   6966:    $question    - The question number to prompt for.
                   6967:    $scan_config - The scantron file configuration hash.
                   6968:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  6969:    $error       - Type of error
1.497     foxr     6970: 
                   6971:  Implicit inputs:
                   6972:    %bubble_lines_per_response   - Starting line numbers for each question.
                   6973:                                   Numbered from 0 (but question numbers are from
                   6974:                                   1.
                   6975:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  6976:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   6977:                                   type problems render as separate sub-questions, 
1.503     raeburn  6978:                                   in exam mode. This hash contains a 
                   6979:                                   comma-separated list of the lines per 
                   6980:                                   sub-question.
1.510     raeburn  6981:    %responsetype_per_response   - essayresponse, formularesponse,
                   6982:                                   stringresponse, imageresponse, reactionresponse,
                   6983:                                   and organicresponse type problem parts can have
1.503     raeburn  6984:                                   multiple lines per response if the weight
                   6985:                                   assigned exceeds 10.  In this case, only
                   6986:                                   one bubble per line is permitted, but more 
                   6987:                                   than one line might contain bubbles, e.g.
                   6988:                                   bubbling of: line 1 - J, line 2 - J, 
                   6989:                                   line 3 - B would assign 22 points.  
1.497     foxr     6990: 
                   6991: =cut
                   6992: 
                   6993: sub prompt_for_corrections {
1.503     raeburn  6994:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   6995:     my ($current_line,$lines);
                   6996:     my @linenums;
                   6997:     my $questionnum = $question;
                   6998:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   6999:         $question = $1;
                   7000:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7001:         my $subquestion = $2;
                   7002:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7003:         my $subcount = 1;
                   7004:         while ($subcount<$subquestion) {
                   7005:             $current_line += $subans[$subcount-1];
                   7006:             $subcount ++;
                   7007:         }
                   7008:         $lines = $subans[$subquestion-1];
                   7009:     } else {
                   7010:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7011:         $lines        = $bubble_lines_per_response{$question-1};
                   7012:     }
1.497     foxr     7013:     if ($lines > 1) {
1.503     raeburn  7014:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7015:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7016:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7017:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7018:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7019:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7020:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.503     raeburn  7021:             $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 scantron sheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during scantron 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 />');
                   7022:         } else {
                   7023:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7024:         }
1.497     foxr     7025:     }
                   7026:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7027:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7028: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7029: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7030:         push(@linenums,$current_line);
1.497     foxr     7031: 	$current_line++;
                   7032:     }
                   7033:     if ($lines > 1) {
                   7034: 	$r->print("<hr /><br />");
                   7035:     }
1.503     raeburn  7036:     return @linenums;
1.157     albertel 7037: }
1.423     albertel 7038: 
                   7039: =pod
                   7040: 
                   7041: =item scantron_bubble_selector
                   7042:   
                   7043:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7044:    possibly showing the existing the selected bubbles if known
1.423     albertel 7045: 
                   7046:  Arguments:
                   7047:     $r           - Apache request object
                   7048:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7049:     $line        - Number of the line being displayed.
1.503     raeburn  7050:     $questionnum - Question number (may include subquestion)
                   7051:     $error       - Type of error.
1.497     foxr     7052:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7053: 
                   7054: =cut
                   7055: 
1.157     albertel 7056: sub scantron_bubble_selector {
1.503     raeburn  7057:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7058:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7059: 
                   7060:     my $scmode=$$scan_config{'Qon'};
                   7061:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7062: 
1.157     albertel 7063:     my @alphabet=('A'..'Z');
1.503     raeburn  7064:     $r->print(&Apache::loncommon::start_data_table().
                   7065:               &Apache::loncommon::start_data_table_row());
                   7066:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7067:     for (my $i=0;$i<$max+1;$i++) {
                   7068: 	$r->print("\n".'<td align="center">');
                   7069: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7070: 	else { $r->print('&nbsp;'); }
                   7071: 	$r->print('</td>');
                   7072:     }
1.503     raeburn  7073:     $r->print(&Apache::loncommon::end_data_table_row().
                   7074:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7075:     for (my $i=0;$i<$max;$i++) {
                   7076: 	$r->print("\n".
                   7077: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7078: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7079:     }
1.503     raeburn  7080:     my $nobub_checked = ' ';
                   7081:     if ($error eq 'missingbubble') {
                   7082:         $nobub_checked = ' checked = "checked" ';
                   7083:     }
                   7084:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7085: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7086:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7087:               $line.'" value="'.$questionnum.'" /></td>');
                   7088:     $r->print(&Apache::loncommon::end_data_table_row().
                   7089:               &Apache::loncommon::end_data_table());
1.157     albertel 7090: }
                   7091: 
1.423     albertel 7092: =pod
                   7093: 
                   7094: =item num_matches
                   7095: 
1.424     albertel 7096:    Counts the number of characters that are the same between the two arguments.
                   7097: 
                   7098:  Arguments:
                   7099:    $orig - CODE from the scanline
                   7100:    $code - CODE to match against
                   7101: 
                   7102:  Returns:
                   7103:    $count - integer count of the number of same characters between the
                   7104:             two arguments
                   7105: 
1.423     albertel 7106: =cut
                   7107: 
1.194     albertel 7108: sub num_matches {
                   7109:     my ($orig,$code) = @_;
                   7110:     my @code=split(//,$code);
                   7111:     my @orig=split(//,$orig);
                   7112:     my $same=0;
                   7113:     for (my $i=0;$i<scalar(@code);$i++) {
                   7114: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7115:     }
                   7116:     return $same;
                   7117: }
                   7118: 
1.423     albertel 7119: =pod
                   7120: 
                   7121: =item scantron_get_closely_matching_CODEs
                   7122: 
1.424     albertel 7123:    Cycles through all CODEs and finds the set that has the greatest
                   7124:    number of same characters as the provided CODE
                   7125: 
                   7126:  Arguments:
                   7127:    $allcodes - hash ref returned by &get_codes()
                   7128:    $CODE     - CODE from the current scanline
                   7129: 
                   7130:  Returns:
                   7131:    2 element list
                   7132:     - first elements is number of how closely matching the best fit is 
                   7133:       (5 means best set has 5 matching characters)
                   7134:     - second element is an arrary ref containing the set of valid CODEs
                   7135:       that best fit the passed in CODE
                   7136: 
1.423     albertel 7137: =cut
                   7138: 
1.194     albertel 7139: sub scantron_get_closely_matching_CODEs {
                   7140:     my ($allcodes,$CODE)=@_;
                   7141:     my @CODEs;
                   7142:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7143: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7144:     }
                   7145: 
                   7146:     return ($#CODEs,$CODEs[-1]);
                   7147: }
                   7148: 
1.423     albertel 7149: =pod
                   7150: 
                   7151: =item get_codes
                   7152: 
1.424     albertel 7153:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7154:    set of remembered CODEs.
                   7155: 
                   7156:  Arguments:
                   7157:   $old_name - name of the set of remembered CODEs
                   7158:   $cdom     - domain of the course
                   7159:   $cnum     - internal course name
                   7160: 
                   7161:  Returns:
                   7162:   %allcodes - keys are the valid CODEs, values are all 1
                   7163: 
1.423     albertel 7164: =cut
                   7165: 
1.194     albertel 7166: sub get_codes {
1.280     foxr     7167:     my ($old_name, $cdom, $cnum) = @_;
                   7168:     if (!$old_name) {
                   7169: 	$old_name=$env{'form.scantron_CODElist'};
                   7170:     }
                   7171:     if (!$cdom) {
                   7172: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7173:     }
                   7174:     if (!$cnum) {
                   7175: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7176:     }
1.278     albertel 7177:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7178: 				    $cdom,$cnum);
                   7179:     my %allcodes;
                   7180:     if ($result{"type\0$old_name"} eq 'number') {
                   7181: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7182:     } else {
                   7183: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7184:     }
1.194     albertel 7185:     return %allcodes;
                   7186: }
                   7187: 
1.423     albertel 7188: =pod
                   7189: 
                   7190: =item scantron_validate_CODE
                   7191: 
1.424     albertel 7192:    Validates all scanlines in the selected file to not have any
                   7193:    invalid or underspecified CODEs and that none of the codes are
                   7194:    duplicated if this was requested.
                   7195: 
1.423     albertel 7196: =cut
                   7197: 
1.157     albertel 7198: sub scantron_validate_CODE {
                   7199:     my ($r,$currentphase) = @_;
1.257     albertel 7200:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7201:     if ($scantron_config{'CODElocation'} &&
                   7202: 	$scantron_config{'CODEstart'} &&
                   7203: 	$scantron_config{'CODElength'}) {
1.257     albertel 7204: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7205: 	    &FIXME_blow_up()
                   7206: 	}
                   7207:     } else {
                   7208: 	return (0,$currentphase+1);
                   7209:     }
                   7210:     
                   7211:     my %usedCODEs;
                   7212: 
1.194     albertel 7213:     my %allcodes=&get_codes();
1.186     albertel 7214: 
1.447     foxr     7215:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   7216: 
1.186     albertel 7217:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7218:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7219: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7220: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7221: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7222: 						 $scan_data);
                   7223: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7224: 	my $error=0;
1.224     albertel 7225: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7226: 	    &scantron_get_correction($r,$i,$scan_record,
                   7227: 				     \%scantron_config,
                   7228: 				     $line,'incorrectCODE',\%allcodes);
                   7229: 	    return(1,$currentphase);
                   7230: 	}
1.221     albertel 7231: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7232: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7233: 	    &scantron_get_correction($r,$i,$scan_record,
                   7234: 				     \%scantron_config,
1.194     albertel 7235: 				     $line,'incorrectCODE',\%allcodes);
                   7236: 	    return(1,$currentphase);
1.186     albertel 7237: 	}
1.214     albertel 7238: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7239: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7240: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7241: 	    &scantron_get_correction($r,$i,$scan_record,
                   7242: 				     \%scantron_config,
1.194     albertel 7243: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7244: 	    return(1,$currentphase);
1.186     albertel 7245: 	}
1.524     raeburn  7246: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7247:     }
1.157     albertel 7248:     return (0,$currentphase+1);
                   7249: }
                   7250: 
1.423     albertel 7251: =pod
                   7252: 
                   7253: =item scantron_validate_doublebubble
                   7254: 
1.424     albertel 7255:    Validates all scanlines in the selected file to not have any
                   7256:    bubble lines with multiple bubbles marked.
                   7257: 
1.423     albertel 7258: =cut
                   7259: 
1.157     albertel 7260: sub scantron_validate_doublebubble {
                   7261:     my ($r,$currentphase) = @_;
                   7262:     #get student info
                   7263:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7264:     my %idmap=&username_to_idmap($classlist);
                   7265: 
                   7266:     #get scantron line setup
1.257     albertel 7267:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7268:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     7269:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   7270: 
1.157     albertel 7271:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7272: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7273: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7274: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7275: 						 $scan_data);
                   7276: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7277: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7278: 				 'doublebubble',
                   7279: 				 $$scan_record{'scantron.doubleerror'});
                   7280:     	return (1,$currentphase);
                   7281:     }
                   7282:     return (0,$currentphase+1);
                   7283: }
                   7284: 
1.423     albertel 7285: 
1.503     raeburn  7286: sub scantron_get_maxbubble {
1.257     albertel 7287:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7288: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7289: 	&restore_bubble_lines();
1.257     albertel 7290: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7291:     }
1.330     albertel 7292: 
1.447     foxr     7293:     my (undef, undef, $sequence) =
1.257     albertel 7294: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7295: 
1.447     foxr     7296:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 7297:     my $map=$navmap->getResourceByUrl($sequence);
                   7298:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7299: 
                   7300:     &Apache::lonxml::clear_problem_counter();
                   7301: 
1.557     raeburn  7302:     my $uname       = $env{'user.name'};
                   7303:     my $udom        = $env{'user.domain'};
1.435     foxr     7304:     my $cid         = $env{'request.course.id'};
                   7305:     my $total_lines = 0;
                   7306:     %bubble_lines_per_response = ();
1.447     foxr     7307:     %first_bubble_line         = ();
1.503     raeburn  7308:     %subdivided_bubble_lines   = ();
                   7309:     %responsetype_per_response = ();
1.554     raeburn  7310: 
1.447     foxr     7311:     my $response_number = 0;
                   7312:     my $bubble_line     = 0;
1.191     albertel 7313:     foreach my $resource (@resources) {
1.542     raeburn  7314:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7315:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7316: 	    foreach my $part_id (@{$parts}) {
                   7317:                 my $lines;
                   7318: 
                   7319: 	        # TODO - make this a persistent hash not an array.
                   7320: 
                   7321:                 # optionresponse, matchresponse and rankresponse type items 
                   7322:                 # render as separate sub-questions in exam mode.
                   7323:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7324:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7325:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7326:                     my ($numbub,$numshown);
                   7327:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7328:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7329:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7330:                         }
                   7331:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7332:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7333:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7334:                         }
                   7335:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7336:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7337:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7338:                         }
                   7339:                     }
                   7340:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7341:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7342:                     }
                   7343:                     my $bubbles_per_line = 10;
                   7344:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7345:                     if (($numbub % $bubbles_per_line) != 0) {
                   7346:                         $inner_bubble_lines++;
                   7347:                     }
                   7348:                     for (my $i=0; $i<$numshown; $i++) {
                   7349:                         $subdivided_bubble_lines{$response_number} .= 
                   7350:                             $inner_bubble_lines.',';
                   7351:                     }
                   7352:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7353:                     $lines = $numshown * $inner_bubble_lines;
                   7354:                 } else {
                   7355:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7356:                 } 
                   7357: 
                   7358:                 $first_bubble_line{$response_number} = $bubble_line;
                   7359: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7360:                 $responsetype_per_response{$response_number} = 
                   7361:                     $analysis->{$part_id.'.type'};
                   7362: 	        $response_number++;
                   7363: 
                   7364: 	        $bubble_line +=  $lines;
                   7365: 	        $total_lines +=  $lines;
                   7366: 	    }
                   7367:         }
                   7368:     }
1.552     raeburn  7369:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7370: 
                   7371:     &save_bubble_lines();
                   7372:     $env{'form.scantron_maxbubble'} =
                   7373: 	$total_lines;
                   7374:     return $env{'form.scantron_maxbubble'};
                   7375: }
1.523     raeburn  7376: 
1.157     albertel 7377: sub scantron_validate_missingbubbles {
                   7378:     my ($r,$currentphase) = @_;
                   7379:     #get student info
                   7380:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7381:     my %idmap=&username_to_idmap($classlist);
                   7382: 
                   7383:     #get scantron line setup
1.257     albertel 7384:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7385:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7386:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7387:     if (!$max_bubble) { $max_bubble=2**31; }
                   7388:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7389: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7390: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7391: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7392: 						 $scan_data);
                   7393: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7394: 	my @to_correct;
1.470     foxr     7395: 	
                   7396: 	# Probably here's where the error is...
                   7397: 
1.157     albertel 7398: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7399:             my $lastbubble;
                   7400:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7401:                my $question = $1;
                   7402:                my $subquestion = $2;
                   7403:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7404:                my $first = $first_bubble_line{$question-1};
                   7405:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7406:                my $subcount = 1;
                   7407:                while ($subcount<$subquestion) {
                   7408:                    $first += $subans[$subcount-1];
                   7409:                    $subcount ++;
                   7410:                }
                   7411:                my $count = $subans[$subquestion-1];
                   7412:                $lastbubble = $first + $count;
                   7413:             } else {
                   7414:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7415:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7416:             }
                   7417:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7418: 	    push(@to_correct,$missing);
                   7419: 	}
                   7420: 	if (@to_correct) {
                   7421: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7422: 				     $line,'missingbubble',\@to_correct);
                   7423: 	    return (1,$currentphase);
                   7424: 	}
                   7425: 
                   7426:     }
                   7427:     return (0,$currentphase+1);
                   7428: }
                   7429: 
1.423     albertel 7430: 
1.82      albertel 7431: sub scantron_process_students {
1.75      albertel 7432:     my ($r) = @_;
1.513     foxr     7433: 
1.257     albertel 7434:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7435:     my ($symb)=&get_symb($r);
1.513     foxr     7436:     if (!$symb) {
                   7437: 	return '';
                   7438:     }
1.324     albertel 7439:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7440: 
1.257     albertel 7441:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7442:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7443:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7444:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7445:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7446:     my $map=$navmap->getResourceByUrl($sequence);
                   7447:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7448:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7449:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7450:                             \%grader_randomlists_by_symb);
                   7451:     foreach my $resource (@resources) {
                   7452:         my $ressymb = $resource->symb();
                   7453:         my ($analysis,$parts) =
                   7454:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7455:                                       $env{'user.name'},$env{'user.domain'},1);
                   7456:         $grader_partids_by_symb{$ressymb} = $parts;
                   7457:         if (ref($analysis) eq 'HASH') {
                   7458:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7459:                 $grader_randomlists_by_symb{$ressymb} = 
                   7460:                     $analysis->{'parts_withrandomlist'};
                   7461:             }
                   7462:         }
                   7463:     }
                   7464: 
1.554     raeburn  7465:     my ($uname,$udom);
1.82      albertel 7466:     my $result= <<SCANTRONFORM;
1.81      albertel 7467: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7468:   <input type="hidden" name="command" value="scantron_configphase" />
                   7469:   $default_form_data
                   7470: SCANTRONFORM
1.82      albertel 7471:     $r->print($result);
                   7472: 
                   7473:     my @delayqueue;
1.542     raeburn  7474:     my (%completedstudents,%scandata);
1.140     albertel 7475:     
1.520     www      7476:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7477:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7478:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7479:  				    'Scantron Progress',$count,
1.195     albertel 7480: 				    'inline',undef,'scantronupload');
1.140     albertel 7481:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7482: 					  'Processing first student');
1.542     raeburn  7483:     $r->print('<br />');
1.140     albertel 7484:     my $start=&Time::HiRes::time();
1.158     albertel 7485:     my $i=-1;
1.542     raeburn  7486:     my $started;
1.447     foxr     7487: 
                   7488:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
1.513     foxr     7489: 
                   7490:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7491:     # the user and return.
                   7492: 
                   7493:     if ($ssi_error) {
                   7494: 	$r->print("</form>");
                   7495: 	&ssi_print_error($r);
                   7496: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7497:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7498: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7499:     }
1.447     foxr     7500: 
1.542     raeburn  7501:     my %lettdig = &letter_to_digits();
                   7502:     my $numletts = scalar(keys(%lettdig));
                   7503: 
1.157     albertel 7504:     while ($i<$scanlines->{'count'}) {
                   7505:  	($uname,$udom)=('','');
                   7506:  	$i++;
1.200     albertel 7507:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7508:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7509: 	if ($started) {
                   7510: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7511: 						     'last student');
                   7512: 	}
                   7513: 	$started=1;
1.157     albertel 7514:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7515:  						 $scan_data);
                   7516:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7517:  					      \%idmap,$i)) {
                   7518:   	    &scantron_add_delay(\@delayqueue,$line,
                   7519:  				'Unable to find a student that matches',1);
                   7520:  	    next;
                   7521:   	}
                   7522:  	if (exists $completedstudents{$uname}) {
                   7523:  	    &scantron_add_delay(\@delayqueue,$line,
                   7524:  				'Student '.$uname.' has multiple sheets',2);
                   7525:  	    next;
                   7526:  	}
                   7527:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7528: 
1.554     raeburn  7529:         my %partids_by_symb;
                   7530:         foreach my $resource (@resources) {
                   7531:             my $ressymb = $resource->symb();
1.557     raeburn  7532:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7533:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7534:                 my ($analysis,$parts) =
                   7535:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7536:                 $partids_by_symb{$ressymb} = $parts;
                   7537:             } else {
                   7538:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7539:             }
1.554     raeburn  7540:         }
                   7541: 
1.330     albertel 7542: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7543:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7544: 
                   7545: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7546: 	    &scantron_putfile($scanlines,$scan_data);
                   7547: 	}
1.161     albertel 7548: 	
1.542     raeburn  7549:         my $scancode;
                   7550:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7551:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7552:             $scancode = $scan_record->{'scantron.CODE'};
                   7553:         } else {
                   7554:             $scancode = '';
                   7555:         }
                   7556: 
                   7557:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7558:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7559:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7560:             $r->print("</form>");
                   7561:             &ssi_print_error($r);
                   7562:             $r->print(&show_grading_menu_form($symb));
                   7563:             &Apache::lonnet::remove_lock($lock);
                   7564:             return '';      # Why return ''?  Beats me.
                   7565:         }
1.513     foxr     7566: 
1.140     albertel 7567: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7568:         if ($env{'form.verifyrecord'}) {
                   7569:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7570:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7571:             chomp($studentdata);
                   7572:             $studentdata =~ s/\r$//;
                   7573:             my $studentrecord = '';
                   7574:             my $counter = -1;
                   7575:             foreach my $resource (@resources) {
1.554     raeburn  7576:                 my $ressymb = $resource->symb();
1.542     raeburn  7577:                 ($counter,my $recording) =
                   7578:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7579:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7580:                                              \%scantron_config,\%lettdig,$numletts);
                   7581:                 $studentrecord .= $recording;
                   7582:             }
                   7583:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7584:                 &Apache::lonxml::clear_problem_counter();
                   7585:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7586:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7587:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7588:                     $r->print("</form>");
                   7589:                     &ssi_print_error($r);
                   7590:                     $r->print(&show_grading_menu_form($symb));
                   7591:                     &Apache::lonnet::remove_lock($lock);
                   7592:                     delete($completedstudents{$uname});
                   7593:                     return '';
                   7594:                 }
1.542     raeburn  7595:                 $counter = -1;
                   7596:                 $studentrecord = '';
                   7597:                 foreach my $resource (@resources) {
1.554     raeburn  7598:                     my $ressymb = $resource->symb();
1.542     raeburn  7599:                     ($counter,my $recording) =
                   7600:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7601:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7602:                                                  \%scantron_config,\%lettdig,$numletts);
                   7603:                     $studentrecord .= $recording;
                   7604:                 }
                   7605:                 if ($studentrecord ne $studentdata) {
                   7606:                     $r->print('<p><span class="LC_error">');
                   7607:                     if ($scancode eq '') {
                   7608:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7609:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7610:                     } else {
                   7611:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7612:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7613:                     }
                   7614:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7615:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7616:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7617:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7618:                               &Apache::loncommon::start_data_table_row().
                   7619:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7620:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7621:                               &Apache::loncommon::end_data_table_row().
                   7622:                               &Apache::loncommon::start_data_table_row().
                   7623:                               '<td>Stored submissions</td>'.
                   7624:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7625:                               &Apache::loncommon::end_data_table_row().
                   7626:                               &Apache::loncommon::end_data_table().'</p>');
                   7627:                 } else {
                   7628:                     $r->print('<br /><span class="LC_warning">'.
                   7629:                              &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 />'.
                   7630:                              &mt("As a consequence, this user's submission history records two tries.").
                   7631:                                  '</span><br />');
                   7632:                 }
                   7633:             }
                   7634:         }
1.543     raeburn  7635:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7636:     } continue {
1.330     albertel 7637: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7638: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7639:     }
1.140     albertel 7640:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7641:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7642: #    my $lasttime = &Time::HiRes::time()-$start;
                   7643: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7644: 
1.200     albertel 7645:     $r->print("</form>");
1.324     albertel 7646:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7647:     return '';
1.75      albertel 7648: }
1.157     albertel 7649: 
1.557     raeburn  7650: sub graders_resources_pass {
                   7651:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7652:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7653:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7654:         foreach my $resource (@{$resources}) {
                   7655:             my $ressymb = $resource->symb();
                   7656:             my ($analysis,$parts) =
                   7657:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7658:                                           $env{'user.name'},$env{'user.domain'},1);
                   7659:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7660:             if (ref($analysis) eq 'HASH') {
                   7661:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7662:                     $grader_randomlists_by_symb->{$ressymb} =
                   7663:                         $analysis->{'parts_withrandomlist'};
                   7664:                 }
                   7665:             }
                   7666:         }
                   7667:     }
                   7668:     return;
                   7669: }
                   7670: 
1.542     raeburn  7671: sub grade_student_bubbles {
1.554     raeburn  7672:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7673:     if (ref($resources) eq 'ARRAY') {
                   7674:         my $count = 0;
                   7675:         foreach my $resource (@{$resources}) {
                   7676:             my $ressymb = $resource->symb();
                   7677:             my %form = ('submitted'      => 'scantron',
                   7678:                         'grade_target'   => 'grade',
                   7679:                         'grade_username' => $uname,
                   7680:                         'grade_domain'   => $udom,
                   7681:                         'grade_courseid' => $env{'request.course.id'},
                   7682:                         'grade_symb'     => $ressymb,
                   7683:                         'CODE'           => $scancode
                   7684:                        );
                   7685:             if (ref($parts) eq 'HASH') {
                   7686:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7687:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7688:                         $form{'scantron_questnum_start.'.$part} =
                   7689:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7690:                         $count++;
                   7691:                     }
                   7692:                 }
                   7693:             }
                   7694:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7695:             return 'ssi_error' if ($ssi_error);
                   7696:             last if (&Apache::loncommon::connection_aborted($r));
                   7697:         }
1.542     raeburn  7698:     }
                   7699:     return;
                   7700: }
                   7701: 
1.157     albertel 7702: sub scantron_upload_scantron_data {
                   7703:     my ($r)=@_;
1.565     raeburn  7704:     my $dom = $env{'request.role.domain'};
                   7705:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7706:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7707:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7708: 							  'domainid',
1.565     raeburn  7709: 							  'coursename',$dom);
                   7710:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7711:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 7712:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7713:     $r->print('
1.157     albertel 7714: <script type="text/javascript" language="javascript">
                   7715:     function checkUpload(formname) {
                   7716: 	if (formname.upfile.value == "") {
1.539     riegler  7717: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.157     albertel 7718: 	    return false;
                   7719: 	}
1.565     raeburn  7720:         if (formname.courseid.value == "") {
                   7721:             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.').'");
                   7722:             return false;
                   7723:         }
1.157     albertel 7724: 	formname.submit();
                   7725:     }
1.565     raeburn  7726: 
                   7727:     function ToSyllabus() {
                   7728:         var cdom = '."'$dom'".';
                   7729:         var cnum = document.rules.courseid.value;
                   7730:         if (cdom == "" || cdom == null) {
                   7731:             return;
                   7732:         }
                   7733:         if (cnum == "" || cnum == null) {
                   7734:            return;
                   7735:         }
                   7736:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7737:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7738:         return;
                   7739:     }
                   7740: 
1.157     albertel 7741: </script>
                   7742: 
1.566     raeburn  7743: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7744: 
1.492     albertel 7745: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7746: '.$default_form_data.
                   7747:   &Apache::lonhtmlcommon::start_pick_box().
                   7748:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7749:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7750:   &Apache::lonhtmlcommon::row_closure().
                   7751:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7752:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7753:   &Apache::lonhtmlcommon::row_closure().
                   7754:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7755:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7756:   &Apache::lonhtmlcommon::row_closure().
                   7757:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7758:   '<input type="file" name="upfile" size="50" />'.
                   7759:   &Apache::lonhtmlcommon::row_closure(1).
                   7760:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7761: 
1.492     albertel 7762: <input name="command" value="scantronupload_save" type="hidden" />
                   7763: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.157     albertel 7764: </form>
1.492     albertel 7765: ');
1.157     albertel 7766:     return '';
                   7767: }
                   7768: 
1.423     albertel 7769: 
1.157     albertel 7770: sub scantron_upload_scantron_data_save {
                   7771:     my($r)=@_;
1.324     albertel 7772:     my ($symb)=&get_symb($r,1);
1.182     albertel 7773:     my $doanotherupload=
                   7774: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7775: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7776: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7777: 	'</form>'."\n";
1.257     albertel 7778:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7779: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7780: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.492     albertel 7781: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
1.182     albertel 7782: 	if ($symb) {
1.324     albertel 7783: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7784: 	} else {
                   7785: 	    $r->print($doanotherupload);
                   7786: 	}
1.162     albertel 7787: 	return '';
                   7788:     }
1.257     albertel 7789:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7790:     my $uploadedfile;
1.567     raeburn  7791:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7792:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7793:         $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 7794:     } else {
1.568     raeburn  7795:         my $result = 
                   7796:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7797:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7798: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7799: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7800:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7801: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7802:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7803:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7804:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7805: 	} else {
1.567     raeburn  7806: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7807:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7808: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7809: 	}
                   7810:     }
1.174     albertel 7811:     if ($symb) {
1.209     ng       7812: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7813:     } else {
1.182     albertel 7814: 	$r->print($doanotherupload);
1.174     albertel 7815:     }
1.157     albertel 7816:     return '';
                   7817: }
                   7818: 
1.567     raeburn  7819: sub validate_uploaded_scantron_file {
                   7820:     my ($cdom,$cname,$fname) = @_;
                   7821:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7822:     my @lines;
                   7823:     if ($scanlines ne '-1') {
                   7824:         @lines=split("\n",$scanlines,-1);
                   7825:     }
                   7826:     my $output;
                   7827:     if (@lines) {
                   7828:         my (%counts,$max_match_format);
                   7829:         my ($max_match_count,$max_match_pct) = (0,0);
                   7830:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7831:         my %idmap = &username_to_idmap($classlist);
                   7832:         foreach my $key (keys(%idmap)) {
                   7833:             my $lckey = lc($key);
                   7834:             $idmap{$lckey} = $idmap{$key};
                   7835:         }
                   7836:         my %unique_formats;
                   7837:         my @formatlines = &get_scantronformat_file();
                   7838:         foreach my $line (@formatlines) {
                   7839:             chomp($line);
                   7840:             my @config = split(/:/,$line);
                   7841:             my $idstart = $config[5];
                   7842:             my $idlength = $config[6];
                   7843:             if (($idstart ne '') && ($idlength > 0)) {
                   7844:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7845:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7846:                 } else {
                   7847:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7848:                 }
                   7849:             }
                   7850:         }
                   7851:         foreach my $key (keys(%unique_formats)) {
                   7852:             my ($idstart,$idlength) = split(':',$key);
                   7853:             %{$counts{$key}} = (
                   7854:                                'found'   => 0,
                   7855:                                'total'   => 0,
                   7856:                               );
                   7857:             foreach my $line (@lines) {
                   7858:                 next if ($line =~ /^#/);
                   7859:                 next if ($line =~ /^[\s\cz]*$/);
                   7860:                 my $id = substr($line,$idstart-1,$idlength);
                   7861:                 $id = lc($id);
                   7862:                 if (exists($idmap{$id})) {
                   7863:                     $counts{$key}{'found'} ++;
                   7864:                 }
                   7865:                 $counts{$key}{'total'} ++;
                   7866:             }
                   7867:             if ($counts{$key}{'total'}) {
                   7868:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7869:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7870:                     $max_match_pct = $percent_match;
                   7871:                     $max_match_format = $key;
                   7872:                     $max_match_count = $counts{$key}{'total'};
                   7873:                 }
                   7874:             }
                   7875:         }
                   7876:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   7877:             my $format_descs;
                   7878:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   7879:             for (my $i=0; $i<$numwithformat; $i++) {
                   7880:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   7881:                 if ($i<$numwithformat-2) {
                   7882:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   7883:                 } elsif ($i==$numwithformat-2) {
                   7884:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   7885:                 } elsif ($i==$numwithformat-1) {
                   7886:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   7887:                 }
                   7888:             }
                   7889:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   7890:             $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).
                   7891:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   7892:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   7893:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   7894:                                   '<i>'.$cdom.'</i>').'</li>'.
                   7895:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   7896:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   7897:                        '</ul>';
                   7898:         }
                   7899:     } else {
                   7900:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   7901:     }
                   7902:     return $output;
                   7903: }
                   7904: 
1.202     albertel 7905: sub valid_file {
                   7906:     my ($requested_file)=@_;
                   7907:     foreach my $filename (sort(&scantron_filenames())) {
                   7908: 	if ($requested_file eq $filename) { return 1; }
                   7909:     }
                   7910:     return 0;
                   7911: }
                   7912: 
                   7913: sub scantron_download_scantron_data {
                   7914:     my ($r)=@_;
1.324     albertel 7915:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7916:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7917:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7918:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7919:     if (! &valid_file($file)) {
1.492     albertel 7920: 	$r->print('
1.202     albertel 7921: 	<p>
1.492     albertel 7922: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7923:         </p>
1.492     albertel 7924: ');
1.324     albertel 7925: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7926: 	return;
                   7927:     }
                   7928:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7929:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7930:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7931:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7932:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7933:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7934:     $r->print('
1.202     albertel 7935:     <p>
1.492     albertel 7936: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7937: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7938:     </p>
                   7939:     <p>
1.492     albertel 7940: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7941: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7942:     </p>
                   7943:     <p>
1.492     albertel 7944: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7945: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7946:     </p>
1.492     albertel 7947: ');
1.324     albertel 7948:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7949:     return '';
                   7950: }
1.157     albertel 7951: 
1.523     raeburn  7952: sub checkscantron_results {
                   7953:     my ($r) = @_;
                   7954:     my ($symb)=&get_symb($r);
                   7955:     if (!$symb) {return '';}
                   7956:     my $grading_menu_button=&show_grading_menu_form($symb);
                   7957:     my $cid = $env{'request.course.id'};
1.542     raeburn  7958:     my %lettdig = &letter_to_digits();
1.523     raeburn  7959:     my $numletts = scalar(keys(%lettdig));
                   7960:     my $cnum = $env{'course.'.$cid.'.num'};
                   7961:     my $cdom = $env{'course.'.$cid.'.domain'};
                   7962:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7963:     my %record;
                   7964:     my %scantron_config =
                   7965:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   7966:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   7967:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7968:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   7969:     my $navmap=Apache::lonnavmaps::navmap->new();
                   7970:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  7971:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7972:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7973:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   7974: 
1.554     raeburn  7975:     my ($uname,$udom);
1.523     raeburn  7976:     my (%scandata,%lastname,%bylast);
                   7977:     $r->print('
                   7978: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   7979: 
                   7980:     my @delayqueue;
                   7981:     my %completedstudents;
                   7982: 
                   7983:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
                   7984:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
                   7985:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
                   7986:                                     'inline',undef,'checkscantron');
1.546     raeburn  7987:     my ($username,$domain,$started);
1.523     raeburn  7988: 
1.557     raeburn  7989:     &scantron_get_maxbubble();  # Need the bubble lines array to parse.
1.523     raeburn  7990: 
                   7991:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7992:                                           'Processing first student');
                   7993:     my $start=&Time::HiRes::time();
                   7994:     my $i=-1;
                   7995: 
                   7996:     while ($i<$scanlines->{'count'}) {
                   7997:         ($username,$domain,$uname)=('','','');
                   7998:         $i++;
                   7999:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8000:         if ($line=~/^[\s\cz]*$/) { next; }
                   8001:         if ($started) {
                   8002:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8003:                                                      'last student');
                   8004:         }
                   8005:         $started=1;
                   8006:         my $scan_record=
                   8007:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8008:                                                      $scan_data);
                   8009:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8010:                                                               \%idmap,$i)) {
                   8011:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8012:                                 'Unable to find a student that matches',1);
                   8013:             next;
                   8014:         }
                   8015:         if (exists $completedstudents{$uname}) {
                   8016:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8017:                                 'Student '.$uname.' has multiple sheets',2);
                   8018:             next;
                   8019:         }
                   8020:         my $pid = $scan_record->{'scantron.ID'};
                   8021:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8022:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8023:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8024:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8025:         chomp($scandata{$pid});
                   8026:         $scandata{$pid} =~ s/\r$//;
                   8027:         ($username,$domain)=split(/:/,$uname);
                   8028:         my $counter = -1;
                   8029:         foreach my $resource (@resources) {
1.557     raeburn  8030:             my $parts;
1.554     raeburn  8031:             my $ressymb = $resource->symb();
1.557     raeburn  8032:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8033:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8034:                 (my $analysis,$parts) =
                   8035:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8036:             } else {
                   8037:                 $parts = $grader_partids_by_symb{$ressymb};
                   8038:             }
1.542     raeburn  8039:             ($counter,my $recording) =
                   8040:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8041:                                          $scandata{$pid},$parts,
1.542     raeburn  8042:                                          \%scantron_config,\%lettdig,$numletts);
                   8043:             $record{$pid} .= $recording;
1.523     raeburn  8044:         }
                   8045:     }
                   8046:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8047:     $r->print('<br />');
                   8048:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8049:     $passed = 0;
                   8050:     $failed = 0;
                   8051:     $numstudents = 0;
                   8052:     foreach my $last (sort(keys(%bylast))) {
                   8053:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8054:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8055:                 my $showscandata = $scandata{$pid};
                   8056:                 my $showrecord = $record{$pid};
                   8057:                 $showscandata =~ s/\s/&nbsp;/g;
                   8058:                 $showrecord =~ s/\s/&nbsp;/g;
                   8059:                 if ($scandata{$pid} eq $record{$pid}) {
                   8060:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8061:                     $okstudents .= '<tr class="'.$css_class.'">'.
                   8062: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8063: '</tr>'."\n".
                   8064: '<tr class="'.$css_class.'">'."\n".
                   8065: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8066:                     $passed ++;
                   8067:                 } else {
                   8068:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
                   8069:                     $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".
                   8070: '</tr>'."\n".
                   8071: '<tr class="'.$css_class.'">'."\n".
                   8072: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8073: '</tr>'."\n";
                   8074:                     $failed ++;
                   8075:                 }
                   8076:                 $numstudents ++;
                   8077:             }
                   8078:         }
                   8079:     }
                   8080:     $r->print('<p>'.&mt('Comparison of scantron 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>');
                   8081:     $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>');
                   8082:     if ($passed) {
                   8083:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
                   8084:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8085:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8086:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8087:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8088:                  $okstudents."\n".
                   8089:                  &Apache::loncommon::end_data_table().'<br />');
                   8090:     }
                   8091:     if ($failed) {
                   8092:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
                   8093:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8094:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8095:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8096:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8097:                  $badstudents."\n".
                   8098:                  &Apache::loncommon::end_data_table()).'<br />'.
                   8099:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
                   8100:     }
                   8101:     $r->print('</form><br />'.$grading_menu_button);
                   8102:     return;
                   8103: }
                   8104: 
1.542     raeburn  8105: sub verify_scantron_grading {
1.554     raeburn  8106:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8107:         $scantron_config,$lettdig,$numletts) = @_;
                   8108:     my ($record,%expected,%startpos);
                   8109:     return ($counter,$record) if (!ref($resource));
                   8110:     return ($counter,$record) if (!$resource->is_problem());
                   8111:     my $symb = $resource->symb();
1.554     raeburn  8112:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8113:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8114:         $counter ++;
                   8115:         $expected{$part_id} = 0;
                   8116:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8117:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8118:             foreach my $item (@sub_lines) {
                   8119:                 $expected{$part_id} += $item;
                   8120:             }
                   8121:         } else {
                   8122:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8123:         }
                   8124:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8125:     }
                   8126:     if ($symb) {
                   8127:         my %recorded;
                   8128:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8129:         if ($returnhash{'version'}) {
                   8130:             my %lasthash=();
                   8131:             my $version;
                   8132:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8133:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8134:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8135:                 }
                   8136:             }
                   8137:             foreach my $key (keys(%lasthash)) {
                   8138:                 if ($key =~ /\.scantron$/) {
                   8139:                     my $value = &unescape($lasthash{$key});
                   8140:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8141:                     if ($value eq '') {
                   8142:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8143:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8144:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8145:                             }
                   8146:                         }
                   8147:                     } else {
                   8148:                         my @tocheck;
                   8149:                         my @items = split(//,$value);
                   8150:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8151:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8152:                             if (@items < $expected{$part_id}) {
                   8153:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8154:                                 my @singles = split(//,$fragment);
                   8155:                                 foreach my $pos (@singles) {
                   8156:                                     if ($pos eq ' ') {
                   8157:                                         push(@tocheck,$pos);
                   8158:                                     } else {
                   8159:                                         my $next = shift(@items);
                   8160:                                         push(@tocheck,$next);
                   8161:                                     }
                   8162:                                 }
                   8163:                             } else {
                   8164:                                 @tocheck = @items;
                   8165:                             }
                   8166:                             foreach my $letter (@tocheck) {
                   8167:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8168:                                     if ($letter !~ /^[A-J]$/) {
                   8169:                                         $letter = $scantron_config->{'Qoff'};
                   8170:                                     }
                   8171:                                     $recorded{$part_id} .= $letter;
                   8172:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8173:                                     my $digit;
                   8174:                                     if ($letter !~ /^[A-J]$/) {
                   8175:                                         $digit = $scantron_config->{'Qoff'};
                   8176:                                     } else {
                   8177:                                         $digit = $lettdig->{$letter};
                   8178:                                     }
                   8179:                                     $recorded{$part_id} .= $digit;
                   8180:                                 }
                   8181:                             }
                   8182:                         } else {
                   8183:                             @tocheck = @items;
                   8184:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8185:                                 my $curr_sub = shift(@tocheck);
                   8186:                                 my $digit;
                   8187:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8188:                                     $digit = $lettdig->{$curr_sub}-1;
                   8189:                                 }
                   8190:                                 if ($curr_sub eq 'J') {
                   8191:                                     $digit += scalar($numletts);
                   8192:                                 }
                   8193:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8194:                                     if ($j == $digit) {
                   8195:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8196:                                     } else {
                   8197:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8198:                                     }
                   8199:                                 }
                   8200:                             }
                   8201:                         }
                   8202:                     }
                   8203:                 }
                   8204:             }
                   8205:         }
1.554     raeburn  8206:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8207:             if ($recorded{$part_id} eq '') {
                   8208:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8209:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8210:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8211:                     }
                   8212:                 }
                   8213:             }
                   8214:             $record .= $recorded{$part_id};
                   8215:         }
                   8216:     }
                   8217:     return ($counter,$record);
                   8218: }
                   8219: 
                   8220: sub letter_to_digits { 
                   8221:     my %lettdig = (
                   8222:                     A => 1,
                   8223:                     B => 2,
                   8224:                     C => 3,
                   8225:                     D => 4,
                   8226:                     E => 5,
                   8227:                     F => 6,
                   8228:                     G => 7,
                   8229:                     H => 8,
                   8230:                     I => 9,
                   8231:                     J => 0,
                   8232:                   );
                   8233:     return %lettdig;
                   8234: }
                   8235: 
1.423     albertel 8236: 
1.75      albertel 8237: #-------- end of section for handling grading scantron forms -------
                   8238: #
                   8239: #-------------------------------------------------------------------
                   8240: 
1.72      ng       8241: #-------------------------- Menu interface -------------------------
                   8242: #
                   8243: #--- Show a Grading Menu button - Calls the next routine ---
                   8244: sub show_grading_menu_form {
1.324     albertel 8245:     my ($symb)=@_;
1.125     ng       8246:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8247: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8248: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8249: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8250: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8251: 	'</form>'."\n";
                   8252:     return $result;
                   8253: }
                   8254: 
1.77      ng       8255: # -- Retrieve choices for grading form
                   8256: sub savedState {
                   8257:     my %savedState = ();
1.257     albertel 8258:     if ($env{'form.saveState'}) {
                   8259: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8260: 	    my ($key,$value) = split(/=/,$_,2);
                   8261: 	    $savedState{$key} = $value;
                   8262: 	}
                   8263:     }
                   8264:     return \%savedState;
                   8265: }
1.76      ng       8266: 
1.443     banghart 8267: sub grading_menu {
                   8268:     my ($request) = @_;
                   8269:     my ($symb)=&get_symb($request);
                   8270:     if (!$symb) {return '';}
                   8271:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8272:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8273: 
1.444     banghart 8274:     $request->print($table);
1.443     banghart 8275:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8276:                   'handgrade'=>$hdgrade,
                   8277:                   'probTitle'=>$probTitle,
                   8278:                   'command'=>'submit_options',
                   8279:                   'saveState'=>"",
                   8280:                   'gradingMenu'=>1,
                   8281:                   'showgrading'=>"yes");
1.538     schulted 8282:     
                   8283:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8284:     
1.443     banghart 8285:     $fields{'command'} = 'csvform';
1.538     schulted 8286:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8287:     
1.443     banghart 8288:     $fields{'command'} = 'processclicker';
1.538     schulted 8289:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8290:     
1.443     banghart 8291:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8292:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8293:     
                   8294:     my @menu = ({	categorytitle=>'Course Grading',
                   8295:             items =>[
                   8296:                         {	linktext => 'Manual Grading/View Submissions',
                   8297:                     		url => $url1,
                   8298:                     		permission => 'F',
                   8299:                     		icon => 'edit-find-replace.png',
                   8300:                     		linktitle => 'Start the process of hand grading submissions.'
                   8301:                         },
                   8302:                 	    {	linktext => 'Upload Scores',
                   8303:                     		url => $url2,
                   8304:                     		permission => 'F',
                   8305:                     		icon => 'uploadscores.png',
                   8306:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8307:                 	    },
                   8308:                 	    {	linktext => 'Process Clicker',
                   8309:                     		url => $url3,
                   8310:                     		permission => 'F',
                   8311:                     		icon => 'addClickerInfoFile.png',
                   8312:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8313:                 	    },
                   8314:                 	    {	linktext => 'Grade/Manage/Review Scantron Forms',
                   8315:                     		url => $url4,
                   8316:                     		permission => 'F',
                   8317:                     		icon => 'stat.png',
                   8318:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
                   8319:                 	    }
                   8320:                     ]
                   8321:             });
                   8322: 
                   8323:     #$fields{'command'} = 'verify';
                   8324:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 8325:     #
                   8326:     # Create the menu
                   8327:     my $Str;
1.444     banghart 8328:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8329:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8330:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8331:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8332: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8333: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8334: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8335: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8336: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8337: 
1.538     schulted 8338:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   8339:     #$menudata->{'jscript'}
                   8340:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
                   8341:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   8342:         ' /> '.
                   8343:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                   8344:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
                   8345: 
1.444     banghart 8346:     $Str .="</form>\n";
1.539     riegler  8347:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 8348:     $request->print(<<GRADINGMENUJS);
                   8349: <script type="text/javascript" language="javascript">
                   8350:     function checkChoice(formname,val,cmdx) {
                   8351: 	if (val <= 2) {
                   8352: 	    var cmd = radioSelection(formname.radioChoice);
                   8353: 	    var cmdsave = cmd;
                   8354: 	} else {
                   8355: 	    cmd = cmdx;
                   8356: 	    cmdsave = 'submission';
                   8357: 	}
                   8358: 	formname.command.value = cmd;
                   8359: 	if (val < 5) formname.submit();
                   8360: 	if (val == 5) {
1.458     banghart 8361: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8362: 	        return false;
                   8363: 	    } else {
                   8364: 	        formname.submit();
                   8365: 	    }
1.445     banghart 8366: 	}
                   8367:     }
1.443     banghart 8368: 
                   8369:     function checkReceiptNo(formname,nospace) {
                   8370: 	var receiptNo = formname.receipt.value;
                   8371: 	var checkOpt = false;
                   8372: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8373: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8374: 	if (checkOpt) {
1.539     riegler  8375: 	    alert("$receiptalert");
1.443     banghart 8376: 	    formname.receipt.value = "";
                   8377: 	    formname.receipt.focus();
                   8378: 	    return false;
                   8379: 	}
                   8380: 	return true;
                   8381:     }
                   8382: </script>
                   8383: GRADINGMENUJS
                   8384:     &commonJSfunctions($request);
                   8385:     return $Str;    
                   8386: }
                   8387: 
                   8388: 
                   8389: #--- Displays the submissions first page -------
                   8390: sub submit_options {
1.72      ng       8391:     my ($request) = @_;
1.324     albertel 8392:     my ($symb)=&get_symb($request);
1.72      ng       8393:     if (!$symb) {return '';}
1.76      ng       8394:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8395: 
1.539     riegler  8396:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       8397:     $request->print(<<GRADINGMENUJS);
                   8398: <script type="text/javascript" language="javascript">
1.116     ng       8399:     function checkChoice(formname,val,cmdx) {
                   8400: 	if (val <= 2) {
                   8401: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8402: 	    var cmdsave = cmd;
1.116     ng       8403: 	} else {
                   8404: 	    cmd = cmdx;
1.118     ng       8405: 	    cmdsave = 'submission';
1.116     ng       8406: 	}
                   8407: 	formname.command.value = cmd;
1.118     ng       8408: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8409: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8410: 	if (val < 5) formname.submit();
                   8411: 	if (val == 5) {
1.72      ng       8412: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8413: 	    formname.submit();
                   8414: 	}
1.238     albertel 8415: 	if (val < 7) formname.submit();
1.72      ng       8416:     }
                   8417: 
                   8418:     function checkReceiptNo(formname,nospace) {
                   8419: 	var receiptNo = formname.receipt.value;
                   8420: 	var checkOpt = false;
                   8421: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8422: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8423: 	if (checkOpt) {
1.539     riegler  8424: 	    alert("$receiptalert");
1.72      ng       8425: 	    formname.receipt.value = "";
                   8426: 	    formname.receipt.focus();
                   8427: 	    return false;
                   8428: 	}
                   8429: 	return true;
                   8430:     }
                   8431: </script>
                   8432: GRADINGMENUJS
1.118     ng       8433:     &commonJSfunctions($request);
1.324     albertel 8434:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8435:     my $result;
1.76      ng       8436:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8437:     my $savedState = &savedState();
1.118     ng       8438:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8439:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8440:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8441:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8442: 
1.533     bisitz   8443:     # Preselect sections
                   8444:     my $selsec="";
                   8445:     if (ref($sections)) {
                   8446:         foreach my $section (sort(@$sections)) {
                   8447:             $selsec.='<option value="'.$section.'" '.
                   8448:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8449:         }
                   8450:     }
                   8451: 
1.72      ng       8452:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8453: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8454: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8455: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8456: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8457: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8458: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8459: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8460: 
1.472     albertel 8461:     $result.='
1.533     bisitz   8462: <h2>
                   8463:   '.&mt('Grade Current Resource').'
                   8464: </h2>
                   8465: <div>
                   8466:   '.$table.'
                   8467: </div>
                   8468: 
1.537     harmsja  8469: <div class="LC_columnSection">
                   8470:   
1.533     bisitz   8471:     <fieldset>
                   8472:       <legend>
                   8473:        '.&mt('Sections').'
                   8474:       </legend>
                   8475:       <select name="section" multiple="multiple" size="5">'."\n";
                   8476:     $result.= $selsec;
1.401     albertel 8477:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8478:     $result.='
1.533     bisitz   8479:     </fieldset>
1.537     harmsja  8480:   
1.533     bisitz   8481:     <fieldset>
                   8482:       <legend>
                   8483:         '.&mt('Groups').'
                   8484:       </legend>
                   8485:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8486:     </fieldset>
1.537     harmsja  8487:   
1.533     bisitz   8488:     <fieldset>
                   8489:       <legend>
                   8490:         '.&mt('Access Status').'
                   8491:       </legend>
                   8492:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8493:     </fieldset>
1.537     harmsja  8494:   
1.533     bisitz   8495:     <fieldset>
                   8496:       <legend>
                   8497:         '.&mt('Submission Status').'
                   8498:       </legend>
                   8499:       <select name="submitonly" size="5">
1.473     albertel 8500: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8501: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8502: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8503: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8504:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   8505:       </select>
                   8506:     </fieldset>
1.537     harmsja  8507:   
1.533     bisitz   8508: </div>
                   8509: 
                   8510: <br />
                   8511:           <div>
                   8512:             <div>
1.473     albertel 8513:               <label>
                   8514:                 <input type="radio" name="radioChoice" value="submission" '.
                   8515:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8516:              &mt('Select individual students to grade and view submissions.').'
                   8517: 	      </label> 
                   8518:             </div>
1.533     bisitz   8519:             <div>
1.473     albertel 8520: 	      <label>
                   8521:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8522:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8523:                     &mt('Grade all selected students in a grading table.').'
                   8524:               </label>
                   8525:             </div>
1.533     bisitz   8526:             <div>
1.539     riegler  8527: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8528:             </div>
1.472     albertel 8529:           </div>
1.533     bisitz   8530: 
                   8531: 
1.473     albertel 8532:         <h2>
                   8533:          '.&mt('Grade Complete Folder for One Student').'
                   8534:         </h2>
1.533     bisitz   8535:         <div>
                   8536:             <div>
1.473     albertel 8537:               <label>
                   8538:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8539: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8540:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8541:               </label>
                   8542:             </div>
1.533     bisitz   8543:             <div>
1.539     riegler  8544: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8545:             </div>
1.472     albertel 8546:         </div>
                   8547:   </form>';
1.499     albertel 8548:     $result .= &show_grading_menu_form($symb);
1.44      ng       8549:     return $result;
1.2       albertel 8550: }
                   8551: 
1.285     albertel 8552: sub reset_perm {
                   8553:     undef(%perm);
                   8554: }
                   8555: 
                   8556: sub init_perm {
                   8557:     &reset_perm();
1.300     albertel 8558:     foreach my $test_perm ('vgr','mgr','opa') {
                   8559: 
                   8560: 	my $scope = $env{'request.course.id'};
                   8561: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8562: 
                   8563: 	    $scope .= '/'.$env{'request.course.sec'};
                   8564: 	    if ( $perm{$test_perm}=
                   8565: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8566: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8567: 	    } else {
                   8568: 		delete($perm{$test_perm});
                   8569: 	    }
1.285     albertel 8570: 	}
                   8571:     }
                   8572: }
                   8573: 
1.400     www      8574: sub gather_clicker_ids {
1.408     albertel 8575:     my %clicker_ids;
1.400     www      8576: 
                   8577:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8578: 
                   8579:     # Set up a couple variables.
1.407     albertel 8580:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8581:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8582:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8583: 
1.407     albertel 8584:     foreach my $student (keys(%$classlist)) {
1.438     www      8585:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8586:         my $username = $classlist->{$student}->[$username_idx];
                   8587:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8588:         my $clickers =
1.408     albertel 8589: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8590:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8591:             $id=~s/^[\#0]+//;
1.421     www      8592:             $id=~s/[\-\:]//g;
1.407     albertel 8593:             if (exists($clicker_ids{$id})) {
1.408     albertel 8594: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8595:             } else {
1.408     albertel 8596: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8597:             }
                   8598:         }
                   8599:     }
1.407     albertel 8600:     return %clicker_ids;
1.400     www      8601: }
                   8602: 
1.402     www      8603: sub gather_adv_clicker_ids {
1.408     albertel 8604:     my %clicker_ids;
1.402     www      8605:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8606:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8607:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8608:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8609:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8610:             my ($puname,$pudom)=split(/\:/,$person);
                   8611:             my $clickers =
1.408     albertel 8612: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8613:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8614: 		$id=~s/^[\#0]+//;
1.421     www      8615:                 $id=~s/[\-\:]//g;
1.408     albertel 8616: 		if (exists($clicker_ids{$id})) {
                   8617: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8618: 		} else {
                   8619: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8620: 		}
1.405     www      8621:             }
1.402     www      8622:         }
                   8623:     }
1.407     albertel 8624:     return %clicker_ids;
1.402     www      8625: }
                   8626: 
1.413     www      8627: sub clicker_grading_parameters {
                   8628:     return ('gradingmechanism' => 'scalar',
                   8629:             'upfiletype' => 'scalar',
                   8630:             'specificid' => 'scalar',
                   8631:             'pcorrect' => 'scalar',
                   8632:             'pincorrect' => 'scalar');
                   8633: }
                   8634: 
1.400     www      8635: sub process_clicker {
                   8636:     my ($r)=@_;
                   8637:     my ($symb)=&get_symb($r);
                   8638:     if (!$symb) {return '';}
                   8639:     my $result=&checkforfile_js();
                   8640:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8641:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8642:     $result.=$table;
                   8643:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8644:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8645:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8646:         '</b></td></tr>'."\n";
1.400     www      8647:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8648: # Attempt to restore parameters from last session, set defaults if not present
                   8649:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8650:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8651:                                                  \%Saveable_Parameters);
                   8652:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8653:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8654:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8655:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8656: 
                   8657:     my %checked;
1.521     www      8658:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8659:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8660:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8661:        }
                   8662:     }
                   8663: 
1.400     www      8664:     my $upload=&mt("Upload File");
                   8665:     my $type=&mt("Type");
1.402     www      8666:     my $attendance=&mt("Award points just for participation");
                   8667:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8668:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8669:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8670:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8671:     my $pcorrect=&mt("Percentage points for correct solution");
                   8672:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8673:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8674: 						   ('iclicker' => 'i>clicker',
                   8675:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8676:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8677:     $result.=<<ENDUPFORM;
1.402     www      8678: <script type="text/javascript">
                   8679: function sanitycheck() {
                   8680: // Accept only integer percentages
                   8681:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8682:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8683: // Find out grading choice
                   8684:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8685:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8686:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8687:       }
                   8688:    }
                   8689: // By default, new choice equals user selection
                   8690:    newgradingchoice=gradingchoice;
                   8691: // Not good to give more points for false answers than correct ones
                   8692:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8693:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8694:    }
                   8695: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8696:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8697:       document.forms.gradesupload.pcorrect.value=100;
                   8698:       document.forms.gradesupload.pincorrect.value=100;
                   8699:    }
                   8700: // If the values are different, cannot be attendance only
                   8701:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8702:        (gradingchoice=='attendance')) {
                   8703:        newgradingchoice='personnel';
                   8704:    }
                   8705: // Change grading choice to new one
                   8706:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8707:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8708:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8709:       } else {
                   8710:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8711:       }
                   8712:    }
                   8713: // Remember the old state
                   8714:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8715: }
                   8716: </script>
1.400     www      8717: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8718: <input type="hidden" name="symb" value="$symb" />
                   8719: <input type="hidden" name="command" value="processclickerfile" />
                   8720: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8721: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8722: <input type="file" name="upfile" size="50" />
                   8723: <br /><label>$type: $selectform</label>
1.569     bisitz   8724: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8725: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8726: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8727: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.569     bisitz   8728: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
1.521     www      8729: <br />&nbsp;&nbsp;&nbsp;
                   8730: <input type="text" name="givenanswer" size="50" />
1.413     www      8731: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8732: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8733: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8734: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8735: </form>
                   8736: ENDUPFORM
                   8737:     $result.='</td></tr></table>'."\n".
                   8738:              '</td></tr></table><br /><br />'."\n";
                   8739:     $result.=&show_grading_menu_form($symb);
                   8740:     return $result;
                   8741: }
                   8742: 
                   8743: sub process_clicker_file {
                   8744:     my ($r)=@_;
                   8745:     my ($symb)=&get_symb($r);
                   8746:     if (!$symb) {return '';}
1.413     www      8747: 
                   8748:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8749:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8750:                                               \%Saveable_Parameters);
                   8751: 
1.400     www      8752:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8753:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8754: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8755: 	return $result.&show_grading_menu_form($symb);
1.404     www      8756:     }
1.522     www      8757:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8758:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8759:         return $result.&show_grading_menu_form($symb);
                   8760:     }
1.522     www      8761:     my $foundgiven=0;
1.521     www      8762:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8763:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8764:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8765:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8766:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8767:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8768:         $foundgiven=$#answers+1;
1.521     www      8769:     }
1.407     albertel 8770:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8771:     my %correct_ids;
1.404     www      8772:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8773: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8774:     }
                   8775:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8776: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8777: 	   $correct_id=~tr/a-z/A-Z/;
                   8778: 	   $correct_id=~s/\s//gs;
                   8779: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8780:            $correct_id=~s/[\-\:]//g;
1.414     www      8781:            if ($correct_id) {
                   8782: 	      $correct_ids{$correct_id}='specified';
                   8783:            }
                   8784:         }
1.400     www      8785:     }
1.404     www      8786:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8787: 	$result.=&mt('Score based on attendance only');
1.521     www      8788:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8789:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8790:     } else {
1.408     albertel 8791: 	my $number=0;
1.411     www      8792: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8793: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8794: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8795: 	    if ($correct_ids{$id} eq 'specified') {
                   8796: 		$result.=&mt('specified');
                   8797: 	    } else {
                   8798: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8799: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8800: 	    }
                   8801: 	    $number++;
                   8802: 	}
1.411     www      8803:         $result.="</p>\n";
1.408     albertel 8804: 	if ($number==0) {
                   8805: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8806: 	    return $result.&show_grading_menu_form($symb);
                   8807: 	}
1.404     www      8808:     }
1.405     www      8809:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8810:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8811: 		     '<span class="LC_error">',
                   8812: 		     '</span>',
                   8813: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8814:         return $result.&show_grading_menu_form($symb);
                   8815:     }
1.410     www      8816: 
                   8817: # Were able to get all the info needed, now analyze the file
                   8818: 
1.411     www      8819:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8820:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8821:     my $heading=&mt('Scanning clicker file');
                   8822:     $result.=(<<ENDHEADER);
                   8823: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8824: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8825: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8826: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8827: <input type="hidden" name="symb" value="$symb" />
                   8828: <input type="hidden" name="command" value="assignclickergrades" />
                   8829: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8830: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8831: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8832: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8833: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8834: ENDHEADER
1.522     www      8835:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8836:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8837:     } 
1.408     albertel 8838:     my %responses;
                   8839:     my @questiontitles;
1.405     www      8840:     my $errormsg='';
                   8841:     my $number=0;
                   8842:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8843: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8844:     }
1.419     www      8845:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8846:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8847:     }
1.411     www      8848:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8849:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8850:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8851:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8852:              '<br />';
1.522     www      8853:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8854:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8855:        return $result.&show_grading_menu_form($symb);
                   8856:     } 
1.414     www      8857: # Remember Question Titles
                   8858: # FIXME: Possibly need delimiter other than ":"
                   8859:     for (my $i=0;$i<$number;$i++) {
                   8860:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8861:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8862:     }
1.411     www      8863:     my $correct_count=0;
                   8864:     my $student_count=0;
                   8865:     my $unknown_count=0;
1.414     www      8866: # Match answers with usernames
                   8867: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8868:     foreach my $id (keys(%responses)) {
1.410     www      8869:        if ($correct_ids{$id}) {
1.414     www      8870:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8871:           $correct_count++;
1.410     www      8872:        } elsif ($clicker_ids{$id}) {
1.437     www      8873:           if ($clicker_ids{$id}=~/\,/) {
                   8874: # More than one user with the same clicker!
                   8875:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8876:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8877:                            "<select name='multi".$id."'>";
                   8878:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8879:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8880:              }
                   8881:              $result.='</select>';
                   8882:              $unknown_count++;
                   8883:           } else {
                   8884: # Good: found one and only one user with the right clicker
                   8885:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8886:              $student_count++;
                   8887:           }
1.410     www      8888:        } else {
1.411     www      8889:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8890:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8891:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8892:                    "\n".&mt("Domain").": ".
                   8893:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8894:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8895:           $unknown_count++;
1.410     www      8896:        }
1.405     www      8897:     }
1.412     www      8898:     $result.='<hr />'.
                   8899:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8900:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8901:        if ($correct_count==0) {
                   8902:           $errormsg.="Found no correct answers answers for grading!";
                   8903:        } elsif ($correct_count>1) {
1.414     www      8904:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8905:        }
                   8906:     }
1.428     www      8907:     if ($number<1) {
                   8908:        $errormsg.="Found no questions.";
                   8909:     }
1.412     www      8910:     if ($errormsg) {
                   8911:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8912:     } else {
                   8913:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8914:     }
                   8915:     $result.='</form></td></tr></table>'."\n".
1.410     www      8916:              '</td></tr></table><br /><br />'."\n";
1.404     www      8917:     return $result.&show_grading_menu_form($symb);
1.400     www      8918: }
                   8919: 
1.405     www      8920: sub iclicker_eval {
1.406     www      8921:     my ($questiontitles,$responses)=@_;
1.405     www      8922:     my $number=0;
                   8923:     my $errormsg='';
                   8924:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8925:         my %components=&Apache::loncommon::record_sep($line);
                   8926:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8927: 	if ($entries[0] eq 'Question') {
                   8928: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8929: 		$$questiontitles[$number]=$entries[$i];
                   8930: 		$number++;
                   8931: 	    }
                   8932: 	}
                   8933: 	if ($entries[0]=~/^\#/) {
                   8934: 	    my $id=$entries[0];
                   8935: 	    my @idresponses;
                   8936: 	    $id=~s/^[\#0]+//;
                   8937: 	    for (my $i=0;$i<$number;$i++) {
                   8938: 		my $idx=3+$i*6;
                   8939: 		push(@idresponses,$entries[$idx]);
                   8940: 	    }
                   8941: 	    $$responses{$id}=join(',',@idresponses);
                   8942: 	}
1.405     www      8943:     }
                   8944:     return ($errormsg,$number);
                   8945: }
                   8946: 
1.419     www      8947: sub interwrite_eval {
                   8948:     my ($questiontitles,$responses)=@_;
                   8949:     my $number=0;
                   8950:     my $errormsg='';
1.420     www      8951:     my $skipline=1;
                   8952:     my $questionnumber=0;
                   8953:     my %idresponses=();
1.419     www      8954:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8955:         my %components=&Apache::loncommon::record_sep($line);
                   8956:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8957:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8958:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8959:         next if $skipline;
                   8960:         if ($entries[0]!=$questionnumber) {
                   8961:            $questionnumber=$entries[0];
                   8962:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8963:            $number++;
1.419     www      8964:         }
1.420     www      8965:         my $id=$entries[4];
                   8966:         $id=~s/^[\#0]+//;
1.421     www      8967:         $id=~s/^v\d*\://i;
                   8968:         $id=~s/[\-\:]//g;
1.420     www      8969:         $idresponses{$id}[$number]=$entries[6];
                   8970:     }
1.524     raeburn  8971:     foreach my $id (keys(%idresponses)) {
1.420     www      8972:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8973:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8974:     }
                   8975:     return ($errormsg,$number);
                   8976: }
                   8977: 
1.414     www      8978: sub assign_clicker_grades {
                   8979:     my ($r)=@_;
                   8980:     my ($symb)=&get_symb($r);
                   8981:     if (!$symb) {return '';}
1.416     www      8982: # See which part we are saving to
                   8983:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8984: # FIXME: This should probably look for the first handgradeable part
                   8985:     my $part=$$partlist[0];
                   8986: # Start screen output
1.414     www      8987:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8988: 
1.414     www      8989:     my $heading=&mt('Assigning grades based on clicker file');
                   8990:     $result.=(<<ENDHEADER);
                   8991: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8992: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8993: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8994: ENDHEADER
                   8995: # Get correct result
                   8996: # FIXME: Possibly need delimiter other than ":"
                   8997:     my @correct=();
1.415     www      8998:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8999:     my $number=$env{'form.number'};
                   9000:     if ($gradingmechanism ne 'attendance') {
1.414     www      9001:        foreach my $key (keys(%env)) {
                   9002:           if ($key=~/^form\.correct\:/) {
                   9003:              my @input=split(/\,/,$env{$key});
                   9004:              for (my $i=0;$i<=$#input;$i++) {
                   9005:                  if (($correct[$i]) && ($input[$i]) &&
                   9006:                      ($correct[$i] ne $input[$i])) {
                   9007:                     $result.='<br /><span class="LC_warning">'.
                   9008:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9009:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9010:                  } elsif ($input[$i]) {
                   9011:                     $correct[$i]=$input[$i];
                   9012:                  }
                   9013:              }
                   9014:           }
                   9015:        }
1.415     www      9016:        for (my $i=0;$i<$number;$i++) {
1.414     www      9017:           if (!$correct[$i]) {
                   9018:              $result.='<br /><span class="LC_error">'.
                   9019:                       &mt('No correct result given for question "[_1]"!',
                   9020:                           $env{'form.question:'.$i}).'</span>';
                   9021:           }
                   9022:        }
                   9023:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9024:     }
                   9025: # Start grading
1.415     www      9026:     my $pcorrect=$env{'form.pcorrect'};
                   9027:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9028:     my $storecount=0;
1.415     www      9029:     foreach my $key (keys(%env)) {
1.420     www      9030:        my $user='';
1.415     www      9031:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9032:           $user=$1;
                   9033:        }
                   9034:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9035:           my $id=$1;
                   9036:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9037:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9038:           } elsif ($env{'form.multi'.$id}) {
                   9039:              $user=$env{'form.multi'.$id};
1.420     www      9040:           }
                   9041:        }
                   9042:        if ($user) { 
1.415     www      9043:           my @answer=split(/\,/,$env{$key});
                   9044:           my $sum=0;
1.522     www      9045:           my $realnumber=$number;
1.415     www      9046:           for (my $i=0;$i<$number;$i++) {
                   9047:              if ($answer[$i]) {
                   9048:                 if ($gradingmechanism eq 'attendance') {
                   9049:                    $sum+=$pcorrect;
1.522     www      9050:                 } elsif ($answer[$i] eq '*') {
                   9051:                    $sum+=$pcorrect;
                   9052:                 } elsif ($answer[$i] eq '-') {
                   9053:                    $realnumber--;
1.415     www      9054:                 } else {
                   9055:                    if ($answer[$i] eq $correct[$i]) {
                   9056:                       $sum+=$pcorrect;
                   9057:                    } else {
                   9058:                       $sum+=$pincorrect;
                   9059:                    }
                   9060:                 }
                   9061:              }
                   9062:           }
1.522     www      9063:           my $ave=$sum/(100*$realnumber);
1.416     www      9064: # Store
                   9065:           my ($username,$domain)=split(/\:/,$user);
                   9066:           my %grades=();
                   9067:           $grades{"resource.$part.solved"}='correct_by_override';
                   9068:           $grades{"resource.$part.awarded"}=$ave;
                   9069:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9070:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9071:                                                  $env{'request.course.id'},
                   9072:                                                  $domain,$username);
                   9073:           if ($returncode ne 'ok') {
                   9074:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9075:           } else {
                   9076:              $storecount++;
                   9077:           }
1.415     www      9078:        }
                   9079:     }
                   9080: # We are done
1.549     hauer    9081:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9082:              '</td></tr></table>'."\n".
1.414     www      9083:              '</td></tr></table><br /><br />'."\n";
                   9084:     return $result.&show_grading_menu_form($symb);
                   9085: }
                   9086: 
1.1       albertel 9087: sub handler {
1.41      ng       9088:     my $request=$_[0];
1.434     albertel 9089:     &reset_caches();
1.257     albertel 9090:     if ($env{'browser.mathml'}) {
1.141     www      9091: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9092:     } else {
1.141     www      9093: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9094:     }
                   9095:     $request->send_http_header;
1.44      ng       9096:     return '' if $request->header_only;
1.41      ng       9097:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9098:     my $symb=&get_symb($request,1);
1.160     albertel 9099:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9100:     my $command=$commands[0];
1.447     foxr     9101: 
1.160     albertel 9102:     if ($#commands > 0) {
                   9103: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9104:     }
1.447     foxr     9105: 
1.513     foxr     9106:     $ssi_error = 0;
1.535     raeburn  9107:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9108:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9109:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9110:     if ($symb eq '' && $command eq '') {
1.257     albertel 9111: 	if ($env{'user.adv'}) {
                   9112: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9113: 		($env{'form.codethree'})) {
                   9114: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9115: 		    $env{'form.codethree'};
1.41      ng       9116: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9117: 		    &Apache::lonnet::checkin($token);
                   9118: 		if ($tsymb) {
1.137     albertel 9119: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9120: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9121: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9122: 					  ('grade_username' => $tuname,
                   9123: 					   'grade_domain' => $tudom,
                   9124: 					   'grade_courseid' => $tcrsid,
                   9125: 					   'grade_symb' => $tsymb)));
1.41      ng       9126: 		    } else {
1.45      ng       9127: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9128: 		    }
1.41      ng       9129: 		} else {
1.45      ng       9130: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9131: 		}
1.14      www      9132: 	    } else {
1.41      ng       9133: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9134: 	    }
                   9135: 	}
                   9136:     } else {
1.285     albertel 9137: 	&init_perm();
1.104     albertel 9138: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9139: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9140: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9141: 	    &pickStudentPage($request);
1.103     albertel 9142: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9143: 	    &displayPage($request);
1.104     albertel 9144: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9145: 	    &updateGradeByPage($request);
1.104     albertel 9146: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9147: 	    &processGroup($request);
1.104     albertel 9148: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9149: 	    $request->print(&grading_menu($request));
                   9150: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9151: 	    $request->print(&submit_options($request));
1.104     albertel 9152: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9153: 	    $request->print(&viewgrades($request));
1.104     albertel 9154: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9155: 	    $request->print(&processHandGrade($request));
1.106     albertel 9156: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9157: 	    $request->print(&editgrades($request));
1.106     albertel 9158: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9159: 	    $request->print(&verifyreceipt($request));
1.400     www      9160:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9161:             $request->print(&process_clicker($request));
                   9162:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9163:             $request->print(&process_clicker_file($request));
1.414     www      9164:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9165:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9166: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9167: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9168: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9169: 	    $request->print(&csvupload($request));
1.106     albertel 9170: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9171: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9172: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9173: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9174: 		$request->print(&csvuploadoptions($request));
1.41      ng       9175: 	    } else {
1.257     albertel 9176: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9177: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9178: 		} else {
1.257     albertel 9179: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9180: 		}
                   9181: 		$request->print(&csvuploadmap($request));
                   9182: 	    }
1.246     albertel 9183: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9184: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9185: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9186: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9187:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9188:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9189: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9190: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9191: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9192: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9193:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9194:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9195: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9196:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9197:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9198:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9199: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9200:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9201:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9202: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9203:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9204:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9205:             $request->print(&checkscantron_results($request));     
1.106     albertel 9206: 	} elsif ($command) {
1.562     bisitz   9207: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9208: 	}
1.2       albertel 9209:     }
1.513     foxr     9210:     if ($ssi_error) {
                   9211: 	&ssi_print_error($request);
                   9212:     }
1.353     albertel 9213:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9214:     &reset_caches();
1.44      ng       9215:     return '';
                   9216: }
                   9217: 
1.1       albertel 9218: 1;
                   9219: 
1.13      albertel 9220: __END__;
1.531     jms      9221: 
                   9222: 
                   9223: =head1 NAME
                   9224: 
                   9225: Apache::grades
                   9226: 
                   9227: =head1 SYNOPSIS
                   9228: 
                   9229: Handles the viewing of grades.
                   9230: 
                   9231: This is part of the LearningOnline Network with CAPA project
                   9232: described at http://www.lon-capa.org.
                   9233: 
                   9234: =head1 OVERVIEW
                   9235: 
                   9236: Do an ssi with retries:
                   9237: While I'd love to factor out this with the vesrion in lonprintout,
                   9238: 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
                   9239: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9240: 
                   9241: At least the logic that drives this has been pulled out into loncommon.
                   9242: 
                   9243: 
                   9244: 
                   9245: ssi_with_retries - Does the server side include of a resource.
                   9246:                      if the ssi call returns an error we'll retry it up to
                   9247:                      the number of times requested by the caller.
                   9248:                      If we still have a proble, no text is appended to the
                   9249:                      output and we set some global variables.
                   9250:                      to indicate to the caller an SSI error occurred.  
                   9251:                      All of this is supposed to deal with the issues described
                   9252:                      in LonCAPA BZ 5631 see:
                   9253:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9254:                      by informing the user that this happened.
                   9255: 
                   9256: Parameters:
                   9257:   resource   - The resource to include.  This is passed directly, without
                   9258:                interpretation to lonnet::ssi.
                   9259:   form       - The form hash parameters that guide the interpretation of the resource
                   9260:                
                   9261:   retries    - Number of retries allowed before giving up completely.
                   9262: Returns:
                   9263:   On success, returns the rendered resource identified by the resource parameter.
                   9264: Side Effects:
                   9265:   The following global variables can be set:
                   9266:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9267:                               It is up to the caller to initialize this to false
                   9268:                               if desired.
                   9269:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9270:                               of the resource that could not be rendered by the ssi
                   9271:                               call.
                   9272:    ssi_error_message   - The error string fetched from the ssi response
                   9273:                               in the event of an error.
                   9274: 
                   9275: 
                   9276: =head1 HANDLER SUBROUTINE
                   9277: 
                   9278: ssi_with_retries()
                   9279: 
                   9280: =head1 SUBROUTINES
                   9281: 
                   9282: =over
                   9283: 
                   9284: =item scantron_get_correction() : 
                   9285: 
                   9286:    Builds the interface screen to interact with the operator to fix a
                   9287:    specific error condition in a specific scanline
                   9288: 
                   9289:  Arguments:
                   9290:     $r           - Apache request object
                   9291:     $i           - number of the current scanline
                   9292:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9293:     $scan_config - hash ref as returned from &get_scantron_config()
                   9294:     $line        - full contents of the current scanline
                   9295:     $error       - error condition, valid values are
                   9296:                    'incorrectCODE', 'duplicateCODE',
                   9297:                    'doublebubble', 'missingbubble',
                   9298:                    'duplicateID', 'incorrectID'
                   9299:     $arg         - extra information needed
                   9300:        For errors:
                   9301:          - duplicateID   - paper number that this studentID was seen before on
                   9302:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9303:                            seen on before
                   9304:          - incorrectCODE - current incorrect CODE 
                   9305:          - doublebubble  - array ref of the bubble lines that have double
                   9306:                            bubble errors
                   9307:          - missingbubble - array ref of the bubble lines that have missing
                   9308:                            bubble errors
                   9309: 
                   9310: =item  scantron_get_maxbubble() : 
                   9311: 
                   9312:    Returns the maximum number of bubble lines that are expected to
                   9313:    occur. Does this by walking the selected sequence rendering the
                   9314:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9315:    for what the current value of the problem counter is.
                   9316: 
                   9317:    Caches the results to $env{'form.scantron_maxbubble'},
                   9318:    $env{'form.scantron.bubble_lines.n'}, 
                   9319:    $env{'form.scantron.first_bubble_line.n'} and
                   9320:    $env{"form.scantron.sub_bubblelines.n"}
                   9321:    which are the total number of bubble, lines, the number of bubble
                   9322:    lines for response n and number of the first bubble line for response n,
                   9323:    and a comma separated list of numbers of bubble lines for sub-questions
                   9324:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9325: 
                   9326: 
                   9327: =item  scantron_validate_missingbubbles() : 
                   9328: 
                   9329:    Validates all scanlines in the selected file to not have any
                   9330:     answers that don't have bubbles that have not been verified
                   9331:     to be bubble free.
                   9332: 
                   9333: =item  scantron_process_students() : 
                   9334: 
                   9335:    Routine that does the actual grading of the bubble sheet information.
                   9336: 
                   9337:    The parsed scanline hash is added to %env 
                   9338: 
                   9339:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9340:    foreach resource , with the form data of
                   9341: 
                   9342: 	'submitted'     =>'scantron' 
                   9343: 	'grade_target'  =>'grade',
                   9344: 	'grade_username'=> username of student
                   9345: 	'grade_domain'  => domain of student
                   9346: 	'grade_courseid'=> of course
                   9347: 	'grade_symb'    => symb of resource to grade
                   9348: 
                   9349:     This triggers a grading pass. The problem grading code takes care
                   9350:     of converting the bubbled letter information (now in %env) into a
                   9351:     valid submission.
                   9352: 
                   9353: =item  scantron_upload_scantron_data() :
                   9354: 
                   9355:     Creates the screen for adding a new bubble sheet data file to a course.
                   9356: 
                   9357: =item  scantron_upload_scantron_data_save() : 
                   9358: 
                   9359:    Adds a provided bubble information data file to the course if user
                   9360:    has the correct privileges to do so. 
                   9361: 
                   9362: =item  valid_file() :
                   9363: 
                   9364:    Validates that the requested bubble data file exists in the course.
                   9365: 
                   9366: =item  scantron_download_scantron_data() : 
                   9367: 
                   9368:    Shows a list of the three internal files (original, corrected,
                   9369:    skipped) for a specific bubble sheet data file that exists in the
                   9370:    course.
                   9371: 
                   9372: =item  scantron_validate_ID() : 
                   9373: 
                   9374:    Validates all scanlines in the selected file to not have any
1.556     weissno  9375:    invalid or underspecified student/employee IDs
1.531     jms      9376: 
                   9377: =back
                   9378: 
                   9379: =cut

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