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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.513.2.2! raeburn     4: # $Id: grades.pm,v 1.513.2.1 2008/03/24 19:08:09 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.456     banghart   38: use Apache::lonpickcode;
1.55      matthew    39: use Apache::loncoursedata;
1.362     albertel   40: use Apache::lonmsg();
1.1       albertel   41: use Apache::Constants qw(:common);
1.167     sakharuk   42: use Apache::lonlocal;
1.386     raeburn    43: use Apache::lonenc;
1.170     albertel   44: use String::Similarity;
1.359     www        45: use LONCAPA;
                     46: 
1.315     bowersj2   47: use POSIX qw(floor);
1.87      www        48: 
1.435     foxr       49: 
1.513     foxr       50: 
1.435     foxr       51: my %perm=();
1.447     foxr       52: 
1.513     foxr       53: #  These variables are used to recover from ssi errors
                     54: 
                     55: my $ssi_retries = 5;
                     56: my $ssi_error;
                     57: my $ssi_error_resource;
                     58: my $ssi_error_message;
                     59: 
                     60: 
                     61: #  Do an ssi with retries:
                     62: #  While I'd love to factor out this with the vesrion in lonprintout,
                     63: #  that would either require a data coupling between modules, which I refuse to perpetuate
                     64: #  (there's quite enough of that already), or would require the invention of another infrastructure
                     65: #  I'm not quite ready to invent (e.g. an ssi_with_retry object).
                     66: #
                     67: # At least the logic that drives this has been pulled out into loncommon.
                     68: 
                     69: 
                     70: #
                     71: #   ssi_with_retries - Does the server side include of a resource.
                     72: #                      if the ssi call returns an error we'll retry it up to
                     73: #                      the number of times requested by the caller.
                     74: #                      If we still have a proble, no text is appended to the
                     75: #                      output and we set some global variables.
1.513.2.2! raeburn    76: #                      to indicate to the caller an SSI error occurred.  
1.513     foxr       77: #                      All of this is supposed to deal with the issues described
                     78: #                      in LonCAPA BZ 5631 see:
                     79: #                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                     80: #                      by informing the user that this happened.
                     81: #
                     82: # Parameters:
                     83: #   resource   - The resource to include.  This is passed directly, without
                     84: #                interpretation to lonnet::ssi.
                     85: #   form       - The form hash parameters that guide the interpretation of the resource
                     86: #                
                     87: #   retries    - Number of retries allowed before giving up completely.
                     88: # Returns:
                     89: #   On success, returns the rendered resource identified by the resource parameter.
                     90: # Side Effects:
                     91: #   The following global variables can be set:
1.513.2.2! raeburn    92: #    ssi_error           - If an unrecoverable error occurred this becomes true.
1.513     foxr       93: #                               It is up to the caller to initialize this to false
                     94: #                               if desired.
1.513.2.2! raeburn    95: #    ssi_error_resource  - If an unrecoverable error occurred, this is the value
1.513     foxr       96: #                               of the resource that could not be rendered by the ssi
                     97: #                               call.
1.513.2.2! raeburn    98: #    ssi_error_message   - The error string fetched from the ssi response
1.513     foxr       99: #                               in the event of an error.
                    100: #
                    101: sub ssi_with_retries {
                    102:     my ($resource, $retries, %form) = @_;
                    103:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                    104:     if ($response->is_error) {
                    105: 	$ssi_error          = 1;
                    106: 	$ssi_error_resource = $resource;
                    107: 	$ssi_error_message  = $response->code . " " . $response->message;
                    108:     }
                    109: 
                    110:     return $content;
                    111: 
                    112: }
                    113: #
                    114: #  Prodcuces an ssi retry failure error message to the user:
                    115: #
                    116: 
                    117: sub ssi_print_error {
                    118:     my ($r) = @_;
1.513.2.2! raeburn   119:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
        !           120:     $r->print('
        !           121: <br />
        !           122: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
        !           123: <p>
        !           124: '.&mt('Unable to retrieve a resource from a server:').'<br />
        !           125: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
        !           126: '.&mt('Error:').' '.$ssi_error_message.'
        !           127: </p>
        !           128: <p>'.
        !           129: &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 />'.
        !           130: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
        !           131: '</p>');
        !           132:     return;
1.513     foxr      133: }
                    134: 
1.44      ng        135: #
1.146     albertel  136: # --- Retrieve the parts from the metadata file.---
1.44      ng        137: sub getpartlist {
1.324     albertel  138:     my ($symb) = @_;
1.439     albertel  139: 
                    140:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    141:     my $res      = $navmap->getBySymb($symb);
                    142:     my $partlist = $res->parts();
                    143:     my $url      = $res->src();
                    144:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    145: 
1.146     albertel  146:     my @stores;
1.439     albertel  147:     foreach my $part (@{ $partlist }) {
1.146     albertel  148: 	foreach my $key (@metakeys) {
                    149: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    150: 	}
                    151:     }
                    152:     return @stores;
1.2       albertel  153: }
                    154: 
1.44      ng        155: # --- Get the symbolic name of a problem and the url
1.324     albertel  156: sub get_symb {
1.173     albertel  157:     my ($request,$silent) = @_;
1.257     albertel  158:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    159:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  160:     if ($symb eq '') { 
                    161: 	if (!$silent) {
                    162: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    163: 	    return ();
                    164: 	}
                    165:     }
1.418     albertel  166:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  167:     return ($symb);
1.32      ng        168: }
                    169: 
1.129     ng        170: #--- Format fullname, username:domain if different for display
                    171: #--- Use anywhere where the student names are listed
                    172: sub nameUserString {
                    173:     my ($type,$fullname,$uname,$udom) = @_;
                    174:     if ($type eq 'header') {
1.485     albertel  175: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        176:     } else {
1.398     albertel  177: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    178: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        179:     }
                    180: }
                    181: 
1.44      ng        182: #--- Get the partlist and the response type for a given problem. ---
                    183: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        184: sub response_type {
1.324     albertel  185:     my ($symb) = shift;
1.377     albertel  186: 
                    187:     my $navmap = Apache::lonnavmaps::navmap->new();
                    188:     my $res = $navmap->getBySymb($symb);
                    189:     my $partlist = $res->parts();
1.392     albertel  190:     my %vPart = 
                    191: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  192:     my (%response_types,%handgrade);
                    193:     foreach my $part (@{ $partlist }) {
1.392     albertel  194: 	next if (%vPart && !exists($vPart{$part}));
                    195: 
1.377     albertel  196: 	my @types = $res->responseType($part);
                    197: 	my @ids = $res->responseIds($part);
                    198: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    199: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    200: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    201: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    202: 				     '.handgrade',$symb);
1.41      ng        203: 	}
                    204:     }
1.377     albertel  205:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        206: }
                    207: 
1.375     albertel  208: sub flatten_responseType {
                    209:     my ($responseType) = @_;
                    210:     my @part_response_id =
                    211: 	map { 
                    212: 	    my $part = $_;
                    213: 	    map {
                    214: 		[$part,$_]
                    215: 		} sort(keys(%{ $responseType->{$part} }));
                    216: 	} sort(keys(%$responseType));
                    217:     return @part_response_id;
                    218: }
                    219: 
1.207     albertel  220: sub get_display_part {
1.324     albertel  221:     my ($partID,$symb)=@_;
1.207     albertel  222:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    223:     if (defined($display) and $display ne '') {
1.398     albertel  224: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  225:     } else {
                    226: 	$display=$partID;
                    227:     }
                    228:     return $display;
                    229: }
1.269     raeburn   230: 
1.118     ng        231: #--- Show resource title
                    232: #--- and parts and response type
                    233: sub showResourceInfo {
1.324     albertel  234:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  235:     my $col=3;
                    236:     if ($checkboxes) { $col=4; }
1.398     albertel  237:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    238:     $result .='<table border="0">';
1.324     albertel  239:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        240:     my %resptype = ();
1.122     ng        241:     my $hdgrade='no';
1.154     albertel  242:     my %partsseen;
1.375     albertel  243:     foreach my $partID (sort keys(%$responseType)) {
                    244: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    245: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    246: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    247: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    248: 	    $result.='<tr>';
                    249: 	    if ($checkboxes) {
                    250: 		if (exists($partsseen{$partID})) {
                    251: 		    $result.="<td>&nbsp;</td>";
                    252: 		} else {
1.401     albertel  253: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  254: 		}
                    255: 		$partsseen{$partID}=1;
1.154     albertel  256: 	    }
1.375     albertel  257: 	    my $display_part=&get_display_part($partID,$symb);
1.485     albertel  258: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
1.398     albertel  259: 		$resID.'</span></td>'.
1.485     albertel  260: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
                    261: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
1.154     albertel  262: 	}
1.118     ng        263:     }
                    264:     $result.='</table>'."\n";
1.147     albertel  265:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        266: }
                    267: 
1.434     albertel  268: sub reset_caches {
                    269:     &reset_analyze_cache();
                    270:     &reset_perm();
                    271: }
                    272: 
                    273: {
                    274:     my %analyze_cache;
1.148     albertel  275: 
1.434     albertel  276:     sub reset_analyze_cache {
                    277: 	undef(%analyze_cache);
                    278:     }
                    279: 
                    280:     sub get_analyze {
                    281: 	my ($symb,$uname,$udom)=@_;
                    282: 	my $key = "$symb\0$uname\0$udom";
                    283: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    284: 
                    285: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    286: 	$url=&Apache::lonnet::clutter($url);
1.513     foxr      287: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
1.513.2.2! raeburn   288: 					   ('grade_target' => 'analyze',
        !           289: 					    'grade_domain' => $udom,
        !           290: 					    'grade_symb' => $symb,
        !           291: 					    'grade_courseid' => 
        !           292: 					     $env{'request.course.id'},
        !           293: 					    'grade_username' => $uname));
1.434     albertel  294: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    295: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    296: 	return $analyze_cache{$key} = \%analyze;
                    297:     }
                    298: 
                    299:     sub get_order {
                    300: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    301: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    302: 	return $analyze->{"$partid.$respid.shown"};
                    303:     }
                    304: 
                    305:     sub get_radiobutton_correct_foil {
                    306: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    307: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    308: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    309: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    310: 		return $foil;
                    311: 	    }
                    312: 	}
                    313:     }
1.148     albertel  314: }
1.434     albertel  315: 
1.118     ng        316: #--- Clean response type for display
1.335     albertel  317: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    318: #        response types only.
1.118     ng        319: sub cleanRecord {
1.336     albertel  320:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    321: 	$uname,$udom) = @_;
1.398     albertel  322:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  323:     if ($response =~ /^(option|rank)$/) {
                    324: 	my %answer=&Apache::lonnet::str2hash($answer);
                    325: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    326: 	my ($toprow,$bottomrow);
                    327: 	foreach my $foil (@$order) {
                    328: 	    if ($grading{$foil} == 1) {
                    329: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    330: 	    } else {
                    331: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    332: 	    }
1.398     albertel  333: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  334: 	}
                    335: 	return '<blockquote><table border="1">'.
1.466     albertel  336: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    337: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  338: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    339:     } elsif ($response eq 'match') {
                    340: 	my %answer=&Apache::lonnet::str2hash($answer);
                    341: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    342: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    343: 	my ($toprow,$middlerow,$bottomrow);
                    344: 	foreach my $foil (@$order) {
                    345: 	    my $item=shift(@items);
                    346: 	    if ($grading{$foil} == 1) {
                    347: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  348: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  349: 	    } else {
                    350: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  351: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  352: 	    }
1.398     albertel  353: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        354: 	}
1.126     ng        355: 	return '<blockquote><table border="1">'.
1.466     albertel  356: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    357: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  358: 	    $middlerow.'</tr>'.
1.466     albertel  359: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  360: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    361:     } elsif ($response eq 'radiobutton') {
                    362: 	my %answer=&Apache::lonnet::str2hash($answer);
                    363: 	my ($toprow,$bottomrow);
1.434     albertel  364: 	my $correct = 
                    365: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    366: 	foreach my $foil (@$order) {
1.148     albertel  367: 	    if (exists($answer{$foil})) {
1.434     albertel  368: 		if ($foil eq $correct) {
1.466     albertel  369: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  370: 		} else {
1.466     albertel  371: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  372: 		}
                    373: 	    } else {
1.466     albertel  374: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  375: 	    }
1.398     albertel  376: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  377: 	}
                    378: 	return '<blockquote><table border="1">'.
1.466     albertel  379: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    380: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  381: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    382:     } elsif ($response eq 'essay') {
1.257     albertel  383: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        384: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  385: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    386: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        387: 
1.257     albertel  388: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    389: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    390: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    391: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    392: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    393: 	    $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        394: 	}
1.166     albertel  395: 	$answer =~ s-\n-<br />-g;
                    396: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  397:     } elsif ( $response eq 'organic') {
                    398: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    399: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    400: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    401: 	return $result;
1.335     albertel  402:     } elsif ( $response eq 'Task') {
                    403: 	if ( $answer eq 'SUBMITTED') {
                    404: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  405: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  406: 	    return $result;
                    407: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    408: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    409: 			       keys(%{$record}));
                    410: 	    return join('<br />',($version,@matches));
                    411: 			       
                    412: 			       
                    413: 	} else {
                    414: 	    my $result =
                    415: 		'<p>'
                    416: 		.&mt('Overall result: [_1]',
                    417: 		     $record->{$version."resource.$respid.$partid.status"})
                    418: 		.'</p>';
                    419: 	    
                    420: 	    $result .= '<ul>';
                    421: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    422: 			     keys(%{$record}));
                    423: 	    foreach my $grade (sort(@grade)) {
                    424: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    425: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    426: 				     $dim, $record->{$grade}).
                    427: 			  '</li>';
                    428: 	    }
                    429: 	    $result.='</ul>';
                    430: 	    return $result;
                    431: 	}
1.440     albertel  432:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    433: 	$answer = 
                    434: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    435: 							      $answer);
1.122     ng        436:     }
1.118     ng        437:     return $answer;
                    438: }
                    439: 
                    440: #-- A couple of common js functions
                    441: sub commonJSfunctions {
                    442:     my $request = shift;
                    443:     $request->print(<<COMMONJSFUNCTIONS);
                    444: <script type="text/javascript" language="javascript">
                    445:     function radioSelection(radioButton) {
                    446: 	var selection=null;
                    447: 	if (radioButton.length > 1) {
                    448: 	    for (var i=0; i<radioButton.length; i++) {
                    449: 		if (radioButton[i].checked) {
                    450: 		    return radioButton[i].value;
                    451: 		}
                    452: 	    }
                    453: 	} else {
                    454: 	    if (radioButton.checked) return radioButton.value;
                    455: 	}
                    456: 	return selection;
                    457:     }
                    458: 
                    459:     function pullDownSelection(selectOne) {
                    460: 	var selection="";
                    461: 	if (selectOne.length > 1) {
                    462: 	    for (var i=0; i<selectOne.length; i++) {
                    463: 		if (selectOne[i].selected) {
                    464: 		    return selectOne[i].value;
                    465: 		}
                    466: 	    }
                    467: 	} else {
1.138     albertel  468:             // only one value it must be the selected one
                    469: 	    return selectOne.value;
1.118     ng        470: 	}
                    471:     }
                    472: </script>
                    473: COMMONJSFUNCTIONS
                    474: }
                    475: 
1.44      ng        476: #--- Dumps the class list with usernames,list of sections,
                    477: #--- section, ids and fullnames for each user.
                    478: sub getclasslist {
1.449     banghart  479:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  480:     my @getsec;
1.450     banghart  481:     my @getgroup;
1.442     banghart  482:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  483:     if (!ref($getsec)) {
                    484: 	if ($getsec ne '' && $getsec ne 'all') {
                    485: 	    @getsec=($getsec);
                    486: 	}
                    487:     } else {
                    488: 	@getsec=@{$getsec};
                    489:     }
                    490:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  491:     if (!ref($getgroup)) {
                    492: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    493: 	    @getgroup=($getgroup);
                    494: 	}
                    495:     } else {
                    496: 	@getgroup=@{$getgroup};
                    497:     }
                    498:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  499: 
1.449     banghart  500:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  501:     # Bail out if we were unable to get the classlist
1.56      matthew   502:     return if (! defined($classlist));
1.449     banghart  503:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   504:     #
                    505:     my %sections;
                    506:     my %fullnames;
1.205     matthew   507:     foreach my $student (keys(%$classlist)) {
                    508:         my $end      = 
                    509:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    510:         my $start    = 
                    511:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    512:         my $id       = 
                    513:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    514:         my $section  = 
                    515:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    516:         my $fullname = 
                    517:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    518:         my $status   = 
                    519:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  520:         my $group   = 
                    521:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        522: 	# filter students according to status selected
1.442     banghart  523: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    524: 	    if (!($stu_status =~ $status)) {
1.450     banghart  525: 		delete($classlist->{$student});
1.76      ng        526: 		next;
                    527: 	    }
                    528: 	}
1.450     banghart  529: 	# filter students according to groups selected
1.453     banghart  530: 	my @stu_groups = split(/,/,$group);
1.450     banghart  531: 	if (@getgroup) {
                    532: 	    my $exclude = 1;
1.454     banghart  533: 	    foreach my $grp (@getgroup) {
                    534: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  535: 	            if ($stu_group eq $grp) {
                    536: 	                $exclude = 0;
                    537:     	            } 
1.450     banghart  538: 	        }
1.453     banghart  539:     	        if (($grp eq 'none') && !$group) {
                    540:         	        $exclude = 0;
                    541:         	}
1.450     banghart  542: 	    }
                    543: 	    if ($exclude) {
                    544: 	        delete($classlist->{$student});
                    545: 	    }
                    546: 	}
1.205     matthew   547: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  548: 	if (&canview($section)) {
1.291     albertel  549: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  550: 		$sections{$section}++;
1.450     banghart  551: 		if ($classlist->{$student}) {
                    552: 		    $fullnames{$student}=$fullname;
                    553: 		}
1.103     albertel  554: 	    } else {
1.205     matthew   555: 		delete($classlist->{$student});
1.103     albertel  556: 	    }
                    557: 	} else {
1.205     matthew   558: 	    delete($classlist->{$student});
1.103     albertel  559: 	}
1.44      ng        560:     }
                    561:     my %seen = ();
1.56      matthew   562:     my @sections = sort(keys(%sections));
                    563:     return ($classlist,\@sections,\%fullnames);
1.44      ng        564: }
                    565: 
1.103     albertel  566: sub canmodify {
                    567:     my ($sec)=@_;
                    568:     if ($perm{'mgr'}) {
                    569: 	if (!defined($perm{'mgr_section'})) {
                    570: 	    # can modify whole class
                    571: 	    return 1;
                    572: 	} else {
                    573: 	    if ($sec eq $perm{'mgr_section'}) {
                    574: 		#can modify the requested section
                    575: 		return 1;
                    576: 	    } else {
                    577: 		# can't modify the request section
                    578: 		return 0;
                    579: 	    }
                    580: 	}
                    581:     }
                    582:     #can't modify
                    583:     return 0;
                    584: }
                    585: 
                    586: sub canview {
                    587:     my ($sec)=@_;
                    588:     if ($perm{'vgr'}) {
                    589: 	if (!defined($perm{'vgr_section'})) {
                    590: 	    # can modify whole class
                    591: 	    return 1;
                    592: 	} else {
                    593: 	    if ($sec eq $perm{'vgr_section'}) {
                    594: 		#can modify the requested section
                    595: 		return 1;
                    596: 	    } else {
                    597: 		# can't modify the request section
                    598: 		return 0;
                    599: 	    }
                    600: 	}
                    601:     }
                    602:     #can't modify
                    603:     return 0;
                    604: }
                    605: 
1.44      ng        606: #--- Retrieve the grade status of a student for all the parts
                    607: sub student_gradeStatus {
1.324     albertel  608:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  609:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        610:     my %partstatus = ();
                    611:     foreach (@$partlist) {
1.128     ng        612: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        613: 	$status              = 'nothing' if ($status eq '');
                    614: 	$partstatus{$_}      = $status;
                    615: 	my $subkey           = "resource.$_.submitted_by";
                    616: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    617:     }
                    618:     return %partstatus;
                    619: }
                    620: 
1.45      ng        621: # hidden form and javascript that calls the form
                    622: # Use by verifyscript and viewgrades
                    623: # Shows a student's view of problem and submission
                    624: sub jscriptNform {
1.324     albertel  625:     my ($symb) = @_;
1.442     banghart  626:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        627:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    628: 	'    function viewOneStudent(user,domain) {'."\n".
                    629: 	'	document.onestudent.student.value = user;'."\n".
                    630: 	'	document.onestudent.userdom.value = domain;'."\n".
                    631: 	'	document.onestudent.submit();'."\n".
                    632: 	'    }'."\n".
                    633: 	'</script>'."\n";
                    634:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  635: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  636: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    637: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  638: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        639: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    640: 	'<input type="hidden" name="student" value="" />'."\n".
                    641: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    642: 	'</form>'."\n";
                    643:     return $jscript;
                    644: }
1.39      ng        645: 
1.447     foxr      646: 
                    647: 
1.315     bowersj2  648: # Given the score (as a number [0-1] and the weight) what is the final
                    649: # point value? This function will round to the nearest tenth, third,
                    650: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  651: sub compute_points {
1.315     bowersj2  652:     my ($score, $weight) = @_;
                    653:     
                    654:     my $tolerance = .00001;
                    655:     my $points = $score * $weight;
                    656: 
                    657:     # Check for nearness to 1/x.
                    658:     my $check_for_nearness = sub {
                    659:         my ($factor) = @_;
                    660:         my $num = ($points * $factor) + $tolerance;
                    661:         my $floored_num = floor($num);
1.316     albertel  662:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  663:             return $floored_num / $factor;
                    664:         }
                    665:         return $points;
                    666:     };
                    667: 
                    668:     $points = $check_for_nearness->(10);
                    669:     $points = $check_for_nearness->(3);
                    670:     $points = $check_for_nearness->(4);
                    671:     
                    672:     return $points;
                    673: }
                    674: 
1.44      ng        675: #------------------ End of general use routines --------------------
1.87      www       676: 
                    677: #
                    678: # Find most similar essay
                    679: #
                    680: 
                    681: sub most_similar {
1.426     albertel  682:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       683: 
                    684: # ignore spaces and punctuation
                    685: 
                    686:     $uessay=~s/\W+/ /gs;
                    687: 
1.282     www       688: # ignore empty submissions (occuring when only files are sent)
                    689: 
                    690:     unless ($uessay=~/\w+/) { return ''; }
                    691: 
1.87      www       692: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       693:     my $limit=0.6;
1.87      www       694:     my $sname='';
                    695:     my $sdom='';
                    696:     my $scrsid='';
                    697:     my $sessay='';
                    698: # go through all essays ...
1.426     albertel  699:     foreach my $tkey (keys(%$old_essays)) {
                    700: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       701: # ... except the same student
1.426     albertel  702:         next if (($tname eq $uname) && ($tdom eq $udom));
                    703: 	my $tessay=$old_essays->{$tkey};
                    704: 	$tessay=~s/\W+/ /gs;
1.87      www       705: # String similarity gives up if not even limit
1.426     albertel  706: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       707: # Found one
1.426     albertel  708: 	if ($tsimilar>$limit) {
                    709: 	    $limit=$tsimilar;
                    710: 	    $sname=$tname;
                    711: 	    $sdom=$tdom;
                    712: 	    $scrsid=$tcrsid;
                    713: 	    $sessay=$old_essays->{$tkey};
                    714: 	}
1.87      www       715:     }
1.88      www       716:     if ($limit>0.6) {
1.87      www       717:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    718:     } else {
                    719:        return ('','','','',0);
                    720:     }
                    721: }
                    722: 
1.44      ng        723: #-------------------------------------------------------------------
                    724: 
                    725: #------------------------------------ Receipt Verification Routines
1.45      ng        726: #
1.44      ng        727: #--- Check whether a receipt number is valid.---
                    728: sub verifyreceipt {
                    729:     my $request  = shift;
                    730: 
1.257     albertel  731:     my $courseid = $env{'request.course.id'};
1.184     www       732:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  733: 	$env{'form.receipt'};
1.44      ng        734:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  735:     my ($symb)   = &get_symb($request);
1.44      ng        736: 
1.487     albertel  737:     my $title.=
                    738: 	'<h3><span class="LC_info">'.
                    739: 	&mt('Verifying Submission Receipt [_1]',$receipt).
                    740: 	'</span></h3>'."\n".
                    741: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    742: 	'</h4>'."\n";
1.44      ng        743: 
                    744:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   745:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  746:     
                    747:     my $receiptparts=0;
1.390     albertel  748:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    749: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  750:     my $parts=['0'];
1.324     albertel  751:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.486     albertel  752:     
                    753:     my $header = 
                    754: 	&Apache::loncommon::start_data_table().
                    755: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  756: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    757: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    758: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  759:     if ($receiptparts) {
1.487     albertel  760: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  761:     }
                    762:     $header.=
                    763: 	&Apache::loncommon::end_data_table_header_row();
                    764: 
1.294     albertel  765:     foreach (sort 
                    766: 	     {
                    767: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    768: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    769: 		 }
                    770: 		 return $a cmp $b;
                    771: 	     } (keys(%$fullname))) {
1.44      ng        772: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  773: 	foreach my $part (@$parts) {
                    774: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  775: 		$contents.=
                    776: 		    &Apache::loncommon::start_data_table_row().
                    777: 		    '<td>&nbsp;'."\n".
1.177     albertel  778: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  779: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  780: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    781: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    782: 		if ($receiptparts) {
                    783: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    784: 		}
1.486     albertel  785: 		$contents.= 
                    786: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  787: 		
                    788: 		$matches++;
                    789: 	    }
1.44      ng        790: 	}
                    791:     }
                    792:     if ($matches == 0) {
1.487     albertel  793: 	$string = $title.&mt('No match found for the above receipt.');
1.44      ng        794:     } else {
1.324     albertel  795: 	$string = &jscriptNform($symb).$title.
1.487     albertel  796: 	    '<p>'.
                    797: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
                    798: 	    '</p>'.
1.486     albertel  799: 	    $header.
                    800: 	    $contents.
                    801: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        802:     }
1.324     albertel  803:     return $string.&show_grading_menu_form($symb);
1.44      ng        804: }
                    805: 
                    806: #--- This is called by a number of programs.
                    807: #--- Called from the Grading Menu - View/Grade an individual student
                    808: #--- Also called directly when one clicks on the subm button 
                    809: #    on the problem page.
1.30      ng        810: sub listStudents {
1.41      ng        811:     my ($request) = shift;
1.49      albertel  812: 
1.324     albertel  813:     my ($symb) = &get_symb($request);
1.257     albertel  814:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    815:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    816:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  817:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  818:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    819:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    820:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    821: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  822: 
1.485     albertel  823:     my $result='<h3><span class="LC_info">&nbsp;'.
                    824: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
                    825: 	.'</span></h3>';
1.118     ng        826: 
1.324     albertel  827:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  828: 
1.485     albertel  829:     my %lt = ( 'multiple' =>
                    830: 	       "Please select a student or group of students before clicking on the Next button.",
                    831: 	       'single'   =>
                    832: 	       "Please select the student before clicking on the Next button.",
                    833: 	       );
                    834:     %lt = &Apache::lonlocal::texthash(%lt);
1.45      ng        835:     $request->print(<<LISTJAVASCRIPT);
                    836: <script type="text/javascript" language="javascript">
1.110     ng        837:     function checkSelect(checkBox) {
                    838: 	var ctr=0;
                    839: 	var sense="";
                    840: 	if (checkBox.length > 1) {
                    841: 	    for (var i=0; i<checkBox.length; i++) {
                    842: 		if (checkBox[i].checked) {
                    843: 		    ctr++;
                    844: 		}
                    845: 	    }
1.485     albertel  846: 	    sense = '$lt{'multiple'}';
1.110     ng        847: 	} else {
                    848: 	    if (checkBox.checked) {
                    849: 		ctr = 1;
                    850: 	    }
1.485     albertel  851: 	    sense = '$lt{'single'}';
1.110     ng        852: 	}
                    853: 	if (ctr == 0) {
1.485     albertel  854: 	    alert(sense);
1.110     ng        855: 	    return false;
                    856: 	}
                    857: 	document.gradesub.submit();
                    858:     }
                    859: 
                    860:     function reLoadList(formname) {
1.112     ng        861: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        862: 	formname.command.value = 'submission';
                    863: 	formname.submit();
                    864:     }
1.45      ng        865: </script>
                    866: LISTJAVASCRIPT
                    867: 
1.118     ng        868:     &commonJSfunctions($request);
1.41      ng        869:     $request->print($result);
1.39      ng        870: 
1.401     albertel  871:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    872:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  873:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  874: 	"\n".$table;
                    875: 	
                    876:     $gradeTable .= 
                    877: 	'&nbsp;'.
                    878: 	&mt('<b>View Problem Text: </b>[_1]',
                    879: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                    880: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
                    881: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
                    882:     $gradeTable .= 
                    883: 	'&nbsp;'.
                    884: 	&mt('<b>View Answer: </b>[_1]',
                    885: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
                    886: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
                    887: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
                    888: 
                    889:     my $submission_options;
1.257     albertel  890:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  891: 	$submission_options.=
                    892: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  893:     }
1.442     banghart  894:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    895:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  896:     $env{'form.Status'} = $saveStatus;
1.485     albertel  897:     $submission_options.=
                    898: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                    899: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                    900: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                    901: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
                    902:     $gradeTable .= 
                    903: 	'&nbsp;'.
                    904: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
                    905: 
                    906:     $gradeTable .= 
                    907:         '&nbsp;'.
                    908: 	&mt('<b>Grading Increments:</b> [_1]',
                    909: 	    '<select name="increment">'.
                    910: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
                    911: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
                    912: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
                    913: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
                    914: 	    '</select>');
                    915:     
                    916:     $gradeTable .= 
1.432     banghart  917:         &build_section_inputs().
1.45      ng        918: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  919: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    920: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    921: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    922: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  923: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        924: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    925: 
1.257     albertel  926:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  927: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        928:     } else {
1.485     albertel  929: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
                    930: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
1.124     ng        931:     }
1.112     ng        932: 
1.485     albertel  933:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    934: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
1.110     ng        935: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  936: 
                    937: # checkall buttons
                    938:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        939:     $gradeTable.='<input type="button" '."\n".
1.45      ng        940: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.485     albertel  941: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
1.249     albertel  942:     $gradeTable.=&check_buttons();
1.485     albertel  943:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
1.450     banghart  944:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  945:     $gradeTable.= &Apache::loncommon::start_data_table().
                    946: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        947:     my $loop = 0;
                    948:     while ($loop < 2) {
1.485     albertel  949: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    950: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  951: 	if ($env{'form.showgrading'} eq 'yes' 
                    952: 	    && $submitonly ne 'queued'
                    953: 	    && $submitonly ne 'all') {
1.485     albertel  954: 	    foreach my $part (sort(@$partlist)) {
                    955: 		my $display_part=
                    956: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    957: 		$gradeTable.=
                    958: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        959: 	    }
1.301     albertel  960: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  961: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        962: 	}
                    963: 	$loop++;
1.126     ng        964: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        965:     }
1.474     albertel  966:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        967: 
1.45      ng        968:     my $ctr = 0;
1.294     albertel  969:     foreach my $student (sort 
                    970: 			 {
                    971: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    972: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    973: 			     }
                    974: 			     return $a cmp $b;
                    975: 			 }
                    976: 			 (keys(%$fullname))) {
1.41      ng        977: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  978: 
1.110     ng        979: 	my %status = ();
1.301     albertel  980: 
                    981: 	if ($submitonly eq 'queued') {
                    982: 	    my %queue_status = 
                    983: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    984: 							$udom,$uname);
                    985: 	    next if (!defined($queue_status{'gradingqueue'}));
                    986: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    987: 	}
                    988: 
                    989: 	if ($env{'form.showgrading'} eq 'yes' 
                    990: 	    && $submitonly ne 'queued'
                    991: 	    && $submitonly ne 'all') {
1.324     albertel  992: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  993: 	    my $submitted = 0;
1.164     albertel  994: 	    my $graded = 0;
1.248     albertel  995: 	    my $incorrect = 0;
1.110     ng        996: 	    foreach (keys(%status)) {
1.145     albertel  997: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  998: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    999: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1000: 		
1.110     ng       1001: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1002: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1003: 		    $submitted = 0;
1.150     albertel 1004: 		    my ($part)=split(/\./,$partid);
1.110     ng       1005: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1006: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1007: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1008: 		}
1.41      ng       1009: 	    }
1.248     albertel 1010: 	    
1.156     albertel 1011: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1012: 				     $submitonly eq 'incorrect' ||
                   1013: 				     $submitonly eq 'graded'));
1.248     albertel 1014: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1015: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1016: 	}
1.34      ng       1017: 
1.45      ng       1018: 	$ctr++;
1.249     albertel 1019: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1020:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1021: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1022: 	    if ($ctr%2 ==1) {
                   1023: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1024: 	    }
1.126     ng       1025: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel 1026:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                   1027:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1028: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1029: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1030: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1031: 
1.257     albertel 1032: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng       1033: 		foreach (sort keys(%status)) {
1.485     albertel 1034: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1035: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1036: 		}
1.41      ng       1037: 	    }
1.126     ng       1038: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1039: 	    if ($ctr%2 ==0) {
                   1040: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1041: 	    }
1.41      ng       1042: 	}
                   1043:     }
1.110     ng       1044:     if ($ctr%2 ==1) {
1.126     ng       1045: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1046: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1047: 		&& $submitonly ne 'queued'
                   1048: 		&& $submitonly ne 'all') {
1.110     ng       1049: 		foreach (@$partlist) {
                   1050: 		    $gradeTable.='<td>&nbsp;</td>';
                   1051: 		}
1.301     albertel 1052: 	    } elsif ($submitonly eq 'queued') {
                   1053: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1054: 	    }
1.474     albertel 1055: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1056:     }
                   1057: 
1.474     albertel 1058:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1059: 	'<input type="button" '.
                   1060: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.485     albertel 1061: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.45      ng       1062:     if ($ctr == 0) {
1.96      albertel 1063: 	my $num_students=(scalar(keys(%$fullname)));
                   1064: 	if ($num_students eq 0) {
1.485     albertel 1065: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1066: 	} else {
1.171     albertel 1067: 	    my $submissions='submissions';
                   1068: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1069: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1070: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1071: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1072: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1073: 		    $num_students).
                   1074: 		'</span><br />';
1.96      albertel 1075: 	}
1.46      ng       1076:     } elsif ($ctr == 1) {
1.474     albertel 1077: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1078:     }
1.324     albertel 1079:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1080:     $request->print($gradeTable);
1.44      ng       1081:     return '';
1.10      ng       1082: }
                   1083: 
1.44      ng       1084: #---- Called from the listStudents routine
1.249     albertel 1085: 
                   1086: sub check_script {
                   1087:     my ($form, $type)=@_;
                   1088:     my $chkallscript='<script type="text/javascript">
                   1089:     function checkall() {
                   1090:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1091:             ele = document.forms.'.$form.'.elements[i];
                   1092:             if (ele.name == "'.$type.'") {
                   1093:             document.forms.'.$form.'.elements[i].checked=true;
                   1094:                                        }
                   1095:         }
                   1096:     }
                   1097: 
                   1098:     function checksec() {
                   1099:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1100:             ele = document.forms.'.$form.'.elements[i];
                   1101:            string = document.forms.'.$form.'.chksec.value;
                   1102:            if
                   1103:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1104:               document.forms.'.$form.'.elements[i].checked=true;
                   1105:             }
                   1106:         }
                   1107:     }
                   1108: 
                   1109: 
                   1110:     function uncheckall() {
                   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=false;
                   1115:                                        }
                   1116:         }
                   1117:     }
                   1118: 
                   1119: </script>'."\n";
                   1120:     return $chkallscript;
                   1121: }
                   1122: 
                   1123: sub check_buttons {
1.485     albertel 1124:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1125:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1126:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1127:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1128:     return $buttons;
                   1129: }
                   1130: 
1.44      ng       1131: #     Displays the submissions for one student or a group of students
1.34      ng       1132: sub processGroup {
1.41      ng       1133:     my ($request)  = shift;
                   1134:     my $ctr        = 0;
1.155     albertel 1135:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1136:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1137: 
1.396     banghart 1138:     foreach my $student (@stuchecked) {
                   1139: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1140: 	$env{'form.student'}        = $uname;
                   1141: 	$env{'form.userdom'}        = $udom;
                   1142: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1143: 	&submission($request,$ctr,$total);
                   1144: 	$ctr++;
                   1145:     }
                   1146:     return '';
1.35      ng       1147: }
1.34      ng       1148: 
1.44      ng       1149: #------------------------------------------------------------------------------------
                   1150: #
                   1151: #-------------------------- Next few routines handles grading by student, essentially
                   1152: #                           handles essay response type problem/part
                   1153: #
                   1154: #--- Javascript to handle the submission page functionality ---
                   1155: sub sub_page_js {
                   1156:     my $request = shift;
                   1157:     $request->print(<<SUBJAVASCRIPT);
                   1158: <script type="text/javascript" language="javascript">
1.71      ng       1159:     function updateRadio(formname,id,weight) {
1.125     ng       1160: 	var gradeBox = formname["GD_BOX"+id];
                   1161: 	var radioButton = formname["RADVAL"+id];
                   1162: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1163: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1164: 	gradeBox.value = pts;
                   1165: 	var resetbox = false;
                   1166: 	if (isNaN(pts) || pts < 0) {
                   1167: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1168: 	    for (var i=0; i<radioButton.length; i++) {
                   1169: 		if (radioButton[i].checked) {
                   1170: 		    gradeBox.value = i;
                   1171: 		    resetbox = true;
                   1172: 		}
                   1173: 	    }
                   1174: 	    if (!resetbox) {
                   1175: 		formtextbox.value = "";
                   1176: 	    }
                   1177: 	    return;
1.44      ng       1178: 	}
1.71      ng       1179: 
                   1180: 	if (pts > weight) {
                   1181: 	    var resp = confirm("You entered a value ("+pts+
                   1182: 			       ") greater than the weight for the part. Accept?");
                   1183: 	    if (resp == false) {
1.125     ng       1184: 		gradeBox.value = oldpts;
1.71      ng       1185: 		return;
                   1186: 	    }
1.44      ng       1187: 	}
1.13      albertel 1188: 
1.71      ng       1189: 	for (var i=0; i<radioButton.length; i++) {
                   1190: 	    radioButton[i].checked=false;
                   1191: 	    if (pts == i && pts != "") {
                   1192: 		radioButton[i].checked=true;
                   1193: 	    }
                   1194: 	}
                   1195: 	updateSelect(formname,id);
1.125     ng       1196: 	formname["stores"+id].value = "0";
1.41      ng       1197:     }
1.5       albertel 1198: 
1.72      ng       1199:     function writeBox(formname,id,pts) {
1.125     ng       1200: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1201: 	if (checkSolved(formname,id) == 'update') {
                   1202: 	    gradeBox.value = pts;
                   1203: 	} else {
1.125     ng       1204: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1205: 	    gradeBox.value = oldpts;
1.125     ng       1206: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1207: 	    for (var i=0; i<radioButton.length; i++) {
                   1208: 		radioButton[i].checked=false;
1.72      ng       1209: 		if (i == oldpts) {
1.71      ng       1210: 		    radioButton[i].checked=true;
                   1211: 		}
                   1212: 	    }
1.41      ng       1213: 	}
1.125     ng       1214: 	formname["stores"+id].value = "0";
1.71      ng       1215: 	updateSelect(formname,id);
                   1216: 	return;
1.41      ng       1217:     }
1.44      ng       1218: 
1.71      ng       1219:     function clearRadBox(formname,id) {
                   1220: 	if (checkSolved(formname,id) == 'noupdate') {
                   1221: 	    updateSelect(formname,id);
                   1222: 	    return;
                   1223: 	}
1.125     ng       1224: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1225: 	for (var i=0; i<gradeSelect.length; i++) {
                   1226: 	    if (gradeSelect[i].selected) {
                   1227: 		var selectx=i;
                   1228: 	    }
                   1229: 	}
1.125     ng       1230: 	var stores = formname["stores"+id];
1.71      ng       1231: 	if (selectx == stores.value) { return };
1.125     ng       1232: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1233: 	gradeBox.value = "";
1.125     ng       1234: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1235: 	for (var i=0; i<radioButton.length; i++) {
                   1236: 	    radioButton[i].checked=false;
                   1237: 	}
                   1238: 	stores.value = selectx;
                   1239:     }
1.5       albertel 1240: 
1.71      ng       1241:     function checkSolved(formname,id) {
1.125     ng       1242: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1243: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1244: 	    if (!reply) {return "noupdate";}
1.120     ng       1245: 	    formname.overRideScore.value = 'yes';
1.41      ng       1246: 	}
1.71      ng       1247: 	return "update";
1.13      albertel 1248:     }
1.71      ng       1249: 
                   1250:     function updateSelect(formname,id) {
1.125     ng       1251: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1252: 	return;
1.41      ng       1253:     }
1.33      ng       1254: 
1.121     ng       1255: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1256:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1257: 	formname.gradeOpt.value = val;
1.71      ng       1258: 	if (val == "Save & Next") {
                   1259: 	    for (i=0;i<=total;i++) {
                   1260: 		for (j=0;j<parttot;j++) {
1.125     ng       1261: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1262: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1263: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1264: 			if (points == "") {
1.125     ng       1265: 			    var name = formname["name"+i].value;
1.129     ng       1266: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1267: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1268: 					       ", part "+partid+". Continue?");
1.71      ng       1269: 			    if (resp == false) {
1.125     ng       1270: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1271: 				return false;
                   1272: 			    }
                   1273: 			}
                   1274: 		    }
                   1275: 		    
                   1276: 		}
                   1277: 	    }
                   1278: 	    
                   1279: 	}
1.121     ng       1280: 	if (val == "Grade Student") {
                   1281: 	    formname.showgrading.value = "yes";
                   1282: 	    if (formname.Status.value == "") {
                   1283: 		formname.Status.value = "Active";
                   1284: 	    }
                   1285: 	    formname.studentNo.value = total;
                   1286: 	}
1.120     ng       1287: 	formname.submit();
                   1288:     }
                   1289: 
1.71      ng       1290: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1291:     function checkSubmitPage(formname,total) {
                   1292: 	noscore = new Array(100);
                   1293: 	var ptr = 0;
                   1294: 	for (i=1;i<total;i++) {
1.125     ng       1295: 	    var partid = formname["q_"+i].value;
1.127     ng       1296: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1297: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1298: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1299: 		if (points == "" && status != "correct_by_student") {
                   1300: 		    noscore[ptr] = i;
                   1301: 		    ptr++;
                   1302: 		}
                   1303: 	    }
                   1304: 	}
                   1305: 	if (ptr != 0) {
                   1306: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1307: 	    var prolist = "";
                   1308: 	    if (ptr == 1) {
                   1309: 		prolist = noscore[0];
                   1310: 	    } else {
                   1311: 		var i = 0;
                   1312: 		while (i < ptr-1) {
                   1313: 		    prolist += noscore[i]+", ";
                   1314: 		    i++;
                   1315: 		}
                   1316: 		prolist += "and "+noscore[i];
                   1317: 	    }
                   1318: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1319: 	    if (resp == false) {
                   1320: 		return false;
                   1321: 	    }
                   1322: 	}
1.45      ng       1323: 
1.71      ng       1324: 	formname.submit();
                   1325:     }
                   1326: </script>
                   1327: SUBJAVASCRIPT
                   1328: }
1.45      ng       1329: 
1.71      ng       1330: #--- javascript for essay type problem --
                   1331: sub sub_page_kw_js {
                   1332:     my $request = shift;
1.80      ng       1333:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1334:     &commonJSfunctions($request);
1.350     albertel 1335: 
1.351     albertel 1336:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1337:     <script text="text/javascript">
                   1338:     function checkInput() {
                   1339:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1340:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1341:       var usrctr = document.msgcenter.usrctr.value;
                   1342:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1343:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1344: 
                   1345:       var msgchk = "";
                   1346:       if (document.msgcenter.subchk.checked) {
                   1347:          msgchk = "msgsub,";
                   1348:       }
                   1349:       var includemsg = 0;
                   1350:       for (var i=1; i<=nmsg; i++) {
                   1351:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1352:           var frmmsg = document.msgcenter["msg"+i];
                   1353:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1354:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1355:           showflg.value = "1";
                   1356:           var chkbox = document.msgcenter["msgn"+i];
                   1357:           if (chkbox.checked) {
                   1358:              msgchk += "savemsg"+i+",";
                   1359:              includemsg = 1;
                   1360:           }
                   1361:       }
                   1362:       if (document.msgcenter.newmsgchk.checked) {
                   1363:          msgchk += "newmsg"+usrctr;
                   1364:          includemsg = 1;
                   1365:       }
                   1366:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1367:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1368:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1369:       includemsg.value = msgchk;
                   1370: 
                   1371:       self.close()
                   1372: 
                   1373:     }
                   1374:     </script>
                   1375: INNERJS
                   1376: 
1.351     albertel 1377:     my $inner_js_highlight_central=<<INNERJS;
                   1378:  <script type="text/javascript">
                   1379:     function updateChoice(flag) {
                   1380:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1381:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1382:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1383:       opener.document.SCORE.refresh.value = "on";
                   1384:       if (opener.document.SCORE.keywords.value!=""){
                   1385:          opener.document.SCORE.submit();
                   1386:       }
                   1387:       self.close()
                   1388:     }
                   1389: </script>
                   1390: INNERJS
                   1391: 
                   1392:     my $start_page_msg_central = 
                   1393:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1394: 				       {'js_ready'  => 1,
                   1395: 					'only_body' => 1,
                   1396: 					'bgcolor'   =>'#FFFFFF',});
                   1397:     my $end_page_msg_central = 
                   1398: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1399: 
                   1400: 
                   1401:     my $start_page_highlight_central = 
                   1402:         &Apache::loncommon::start_page('Highlight Central',
                   1403: 				       $inner_js_highlight_central,
1.350     albertel 1404: 				       {'js_ready'  => 1,
                   1405: 					'only_body' => 1,
                   1406: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1407:     my $end_page_highlight_central = 
1.350     albertel 1408: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1409: 
1.219     www      1410:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1411:     $docopen=~s/^document\.//;
1.71      ng       1412:     $request->print(<<SUBJAVASCRIPT);
                   1413: <script type="text/javascript" language="javascript">
1.45      ng       1414: 
1.44      ng       1415: //===================== Show list of keywords ====================
1.122     ng       1416:   function keywords(formname) {
                   1417:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1418:     if (nret==null) return;
1.122     ng       1419:     formname.keywords.value = nret;
1.44      ng       1420: 
1.122     ng       1421:     if (formname.keywords.value != "") {
1.128     ng       1422: 	formname.refresh.value = "on";
1.122     ng       1423: 	formname.submit();
1.44      ng       1424:     }
                   1425:     return;
                   1426:   }
                   1427: 
                   1428: //===================== Script to view submitted by ==================
                   1429:   function viewSubmitter(submitter) {
                   1430:     document.SCORE.refresh.value = "on";
                   1431:     document.SCORE.NCT.value = "1";
                   1432:     document.SCORE.unamedom0.value = submitter;
                   1433:     document.SCORE.submit();
                   1434:     return;
                   1435:   }
                   1436: 
                   1437: //===================== Script to add keyword(s) ==================
                   1438:   function getSel() {
                   1439:     if (document.getSelection) txt = document.getSelection();
                   1440:     else if (document.selection) txt = document.selection.createRange().text;
                   1441:     else return;
                   1442:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1443:     if (cleantxt=="") {
1.46      ng       1444: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1445: 	return;
                   1446:     }
                   1447:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1448:     if (nret==null) return;
1.127     ng       1449:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1450:     if (document.SCORE.keywords.value != "") {
1.127     ng       1451: 	document.SCORE.refresh.value = "on";
1.44      ng       1452: 	document.SCORE.submit();
                   1453:     }
                   1454:     return;
                   1455:   }
                   1456: 
                   1457: //====================== Script for composing message ==============
1.80      ng       1458:    // preload images
                   1459:    img1 = new Image();
                   1460:    img1.src = "$iconpath/mailbkgrd.gif";
                   1461:    img2 = new Image();
                   1462:    img2.src = "$iconpath/mailto.gif";
                   1463: 
1.44      ng       1464:   function msgCenter(msgform,usrctr,fullname) {
                   1465:     var Nmsg  = msgform.savemsgN.value;
                   1466:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1467:     var subject = msgform.msgsub.value;
1.127     ng       1468:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1469:     re = /msgsub/;
                   1470:     var shwsel = "";
                   1471:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1472:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1473:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1474:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1475: 	var testmsg = "savemsg"+i+",";
                   1476: 	re = new RegExp(testmsg,"g");
1.44      ng       1477: 	shwsel = "";
                   1478: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1479: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1480: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1481: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1482: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1483:     }
1.125     ng       1484:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1485:     shwsel = "";
                   1486:     re = /newmsg/;
                   1487:     if (re.test(msgchk)) { shwsel = "checked" }
                   1488:     newMsg(newmsg,shwsel);
                   1489:     msgTail(); 
                   1490:     return;
                   1491:   }
                   1492: 
1.123     ng       1493:   function checkEntities(strx) {
                   1494:     if (strx.length == 0) return strx;
                   1495:     var orgStr = ["&", "<", ">", '"']; 
                   1496:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1497:     var counter = 0;
                   1498:     while (counter < 4) {
                   1499: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1500: 	counter++;
                   1501:     }
                   1502:     return strx;
                   1503:   }
                   1504: 
                   1505:   function strReplace(strx, orgStr, newStr) {
                   1506:     return strx.split(orgStr).join(newStr);
                   1507:   }
                   1508: 
1.44      ng       1509:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1510:     var height = 70*Nmsg+250;
1.44      ng       1511:     var scrollbar = "no";
                   1512:     if (height > 600) {
                   1513: 	height = 600;
                   1514: 	scrollbar = "yes";
                   1515:     }
1.118     ng       1516:     var xpos = (screen.width-600)/2;
                   1517:     xpos = (xpos < 0) ? '0' : xpos;
                   1518:     var ypos = (screen.height-height)/2-30;
                   1519:     ypos = (ypos < 0) ? '0' : ypos;
                   1520: 
1.206     albertel 1521:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1522:     pWin.focus();
                   1523:     pDoc = pWin.document;
1.219     www      1524:     pDoc.$docopen;
1.351     albertel 1525:     pDoc.write('$start_page_msg_central');
1.76      ng       1526: 
                   1527:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1528:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1529:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1530: 
                   1531:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1532:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1533:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1534: }
                   1535:     function displaySubject(msg,shwsel) {
1.76      ng       1536:     pDoc = pWin.document;
                   1537:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1538:     pDoc.write("<td>Subject<\\/td>");
                   1539:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1540:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1541: }
                   1542: 
1.72      ng       1543:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1544:     pDoc = pWin.document;
                   1545:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1546:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1547:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1548:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1549: }
                   1550: 
                   1551:   function newMsg(newmsg,shwsel) {
1.76      ng       1552:     pDoc = pWin.document;
                   1553:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1554:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1555:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1556:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1557: }
                   1558: 
                   1559:   function msgTail() {
1.76      ng       1560:     pDoc = pWin.document;
1.465     albertel 1561:     pDoc.write("<\\/table>");
                   1562:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1563:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1564:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1565:     pDoc.write("<\\/form>");
1.351     albertel 1566:     pDoc.write('$end_page_msg_central');
1.128     ng       1567:     pDoc.close();
1.44      ng       1568: }
                   1569: 
                   1570: //====================== Script for keyword highlight options ==============
                   1571:   function kwhighlight() {
                   1572:     var kwclr    = document.SCORE.kwclr.value;
                   1573:     var kwsize   = document.SCORE.kwsize.value;
                   1574:     var kwstyle  = document.SCORE.kwstyle.value;
                   1575:     var redsel = "";
                   1576:     var grnsel = "";
                   1577:     var blusel = "";
                   1578:     if (kwclr=="red")   {var redsel="checked"};
                   1579:     if (kwclr=="green") {var grnsel="checked"};
                   1580:     if (kwclr=="blue")  {var blusel="checked"};
                   1581:     var sznsel = "";
                   1582:     var sz1sel = "";
                   1583:     var sz2sel = "";
                   1584:     if (kwsize=="0")  {var sznsel="checked"};
                   1585:     if (kwsize=="+1") {var sz1sel="checked"};
                   1586:     if (kwsize=="+2") {var sz2sel="checked"};
                   1587:     var synsel = "";
                   1588:     var syisel = "";
                   1589:     var sybsel = "";
                   1590:     if (kwstyle=="")    {var synsel="checked"};
                   1591:     if (kwstyle=="<i>") {var syisel="checked"};
                   1592:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1593:     highlightCentral();
                   1594:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1595:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1596:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1597:     highlightend();
                   1598:     return;
                   1599:   }
                   1600: 
                   1601:   function highlightCentral() {
1.76      ng       1602: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1603:     var xpos = (screen.width-400)/2;
                   1604:     xpos = (xpos < 0) ? '0' : xpos;
                   1605:     var ypos = (screen.height-330)/2-30;
                   1606:     ypos = (ypos < 0) ? '0' : ypos;
                   1607: 
1.206     albertel 1608:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1609:     hwdWin.focus();
                   1610:     var hDoc = hwdWin.document;
1.219     www      1611:     hDoc.$docopen;
1.351     albertel 1612:     hDoc.write('$start_page_highlight_central');
1.76      ng       1613:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1614:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1615: 
                   1616:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1617:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1618:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1619:   }
                   1620: 
                   1621:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1622:     var hDoc = hwdWin.document;
                   1623:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1624:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1625:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1626:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1627:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1628:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1629:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1630:     hDoc.write("<\\/tr>");
1.44      ng       1631:   }
                   1632: 
                   1633:   function highlightend() { 
1.76      ng       1634:     var hDoc = hwdWin.document;
1.465     albertel 1635:     hDoc.write("<\\/table>");
                   1636:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1637:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1638:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1639:     hDoc.write("<\\/form>");
1.351     albertel 1640:     hDoc.write('$end_page_highlight_central');
1.128     ng       1641:     hDoc.close();
1.44      ng       1642:   }
                   1643: 
                   1644: </script>
                   1645: SUBJAVASCRIPT
                   1646: }
                   1647: 
1.349     albertel 1648: sub get_increment {
1.348     bowersj2 1649:     my $increment = $env{'form.increment'};
                   1650:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1651:         $increment != .1) {
                   1652:         $increment = 1;
                   1653:     }
                   1654:     return $increment;
                   1655: }
                   1656: 
1.71      ng       1657: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1658: sub gradeBox {
1.322     albertel 1659:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1660:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1661: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1662:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1663:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1664:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1665:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1666:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1667: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1668:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1669:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1670:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1671: 				       [$partid]);
                   1672:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1673:     if ($last_resets{$partid}) {
                   1674:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1675:     }
1.485     albertel 1676:     $result.='<table border="0"><tr>';
1.71      ng       1677:     my $ctr = 0;
1.348     bowersj2 1678:     my $thisweight = 0;
1.349     albertel 1679:     my $increment = &get_increment();
1.485     albertel 1680: 
                   1681:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1682:     while ($thisweight<=$wgt) {
1.485     albertel 1683: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1684: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1685: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1686: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1687: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1688:         $thisweight += $increment;
1.71      ng       1689: 	$ctr++;
                   1690:     }
1.485     albertel 1691:     $radio.='</tr></table>';
                   1692: 
                   1693:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1694: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1695: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1696: 	$wgt.')" /></td>'."\n";
1.485     albertel 1697:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1698: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1699: 	' </td><td>'."\n";
1.485     albertel 1700:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1701: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1702:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1703: 	$line.='<option></option>'.
                   1704: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1705:     } else {
1.485     albertel 1706: 	$line.='<option selected="selected"></option>'.
                   1707: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1708:     }
1.485     albertel 1709:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1710: 
                   1711: 
                   1712:     $result .= 
                   1713: 	&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);
                   1714: 
                   1715:     
                   1716:     $result.='</tr></table>'."\n";
1.71      ng       1717:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1718: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1719: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1720: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1721:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1722:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1723:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1724:         $aggtries.'" />'."\n";
1.323     banghart 1725:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1726:     return $result;
                   1727: }
1.322     albertel 1728: 
                   1729: sub handback_box {
1.323     banghart 1730:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1731:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1732:     my (@respids);
1.375     albertel 1733:      my @part_response_id = &flatten_responseType($responseType);
                   1734:     foreach my $part_response_id (@part_response_id) {
                   1735:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1736:         if ($part eq $partid) {
1.375     albertel 1737:             push(@respids,$resp);
1.323     banghart 1738:         }
                   1739:     }
1.318     banghart 1740:     my $result;
1.323     banghart 1741:     foreach my $respid (@respids) {
1.322     albertel 1742: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1743: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1744: 	next if (!@$files);
                   1745: 	my $file_counter = 1;
1.313     banghart 1746: 	foreach my $file (@$files) {
1.368     banghart 1747: 	    if ($file =~ /\/portfolio\//) {
                   1748:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1749:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1750:     	        $file_disp = "$name.$ext";
                   1751:     	        $file = $file_path.$file_disp;
                   1752:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1753:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1754:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1755:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1756:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1757:     	        $file_counter++;
                   1758: 	    }
1.322     albertel 1759: 	}
1.313     banghart 1760:     }
1.318     banghart 1761:     return $result;    
1.71      ng       1762: }
1.44      ng       1763: 
1.58      albertel 1764: sub show_problem {
1.382     albertel 1765:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1766:     my $rendered;
1.382     albertel 1767:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1768:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1769:     if ($mode eq 'both' or $mode eq 'text') {
                   1770: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1771: 						       $env{'request.course.id'},
                   1772: 						       undef,\%form);
1.144     albertel 1773:     }
1.58      albertel 1774:     if ($removeform) {
                   1775: 	$rendered=~s|<form(.*?)>||g;
                   1776: 	$rendered=~s|</form>||g;
1.374     albertel 1777: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1778:     }
1.144     albertel 1779:     my $companswer;
                   1780:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1781: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1782: 	$companswer=
                   1783: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1784: 						    $env{'request.course.id'},
                   1785: 						    %form);
1.144     albertel 1786:     }
1.58      albertel 1787:     if ($removeform) {
                   1788: 	$companswer=~s|<form(.*?)>||g;
                   1789: 	$companswer=~s|</form>||g;
1.144     albertel 1790: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1791:     }
1.468     albertel 1792:     $rendered=
                   1793: 	'<div class="LC_grade_show_problem_header">'.
                   1794: 	&mt('View of the problem').
                   1795: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1796: 	$rendered.
                   1797: 	'</div>';
                   1798:     $companswer=
                   1799: 	'<div class="LC_grade_show_problem_header">'.
                   1800: 	&mt('Correct answer').
                   1801: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1802: 	$companswer.
                   1803: 	'</div>';
                   1804:     my $result;
1.144     albertel 1805:     if ($mode eq 'both') {
1.468     albertel 1806: 	$result=$rendered.$companswer;
1.144     albertel 1807:     } elsif ($mode eq 'text') {
1.468     albertel 1808: 	$result=$rendered;
1.144     albertel 1809:     } elsif ($mode eq 'answer') {
1.468     albertel 1810: 	$result=$companswer;
1.144     albertel 1811:     }
1.468     albertel 1812:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1813:     return $result;
1.58      albertel 1814: }
1.397     albertel 1815: 
1.396     banghart 1816: sub files_exist {
                   1817:     my ($r, $symb) = @_;
                   1818:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1819: 
1.396     banghart 1820:     foreach my $student (@students) {
                   1821:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1822:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1823: 					      $udom,$uname);
1.396     banghart 1824:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1825:         foreach my $submission (@$string) {
                   1826:             my ($partid,$respid) =
                   1827: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1828:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1829: 					   \%record);
                   1830:             return 1 if (@$files);
1.396     banghart 1831:         }
                   1832:     }
1.397     albertel 1833:     return 0;
1.396     banghart 1834: }
1.397     albertel 1835: 
1.394     banghart 1836: sub download_all_link {
                   1837:     my ($r,$symb) = @_;
1.395     albertel 1838:     my $all_students = 
                   1839: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1840: 
                   1841:     my $parts =
                   1842: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1843: 
1.394     banghart 1844:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1845:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1846:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1847:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1848:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1849: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1850:     return
                   1851: }
1.395     albertel 1852: 
1.432     banghart 1853: sub build_section_inputs {
                   1854:     my $section_inputs;
                   1855:     if ($env{'form.section'} eq '') {
                   1856:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1857:     } else {
                   1858:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1859:         foreach my $section (@sections) {
1.432     banghart 1860:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1861:         }
                   1862:     }
                   1863:     return $section_inputs;
                   1864: }
                   1865: 
1.44      ng       1866: # --------------------------- show submissions of a student, option to grade 
                   1867: sub submission {
                   1868:     my ($request,$counter,$total) = @_;
1.257     albertel 1869:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1870:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1871:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1872:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1873:     my $symb = &get_symb($request); 
                   1874:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1875: 
                   1876:     if (!&canview($usec)) {
1.398     albertel 1877: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1878: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1879: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1880: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1881: 	return;
                   1882:     }
                   1883: 
1.257     albertel 1884:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1885:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1886:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1887:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1888:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1889: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1890: 	'/check.gif" height="16" border="0" />';
1.41      ng       1891: 
1.426     albertel 1892:     my %old_essays;
1.41      ng       1893:     # header info
                   1894:     if ($counter == 0) {
                   1895: 	&sub_page_js($request);
1.257     albertel 1896: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1897: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1898: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1899: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1900: 	    &download_all_link($request, $symb);
                   1901: 	}
1.485     albertel 1902: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1903: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1904: 
1.44      ng       1905: 	# option to display problem, only once else it cause problems 
                   1906:         # with the form later since the problem has a form.
1.257     albertel 1907: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1908: 	    my $mode;
1.257     albertel 1909: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1910: 		$mode='both';
1.257     albertel 1911: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1912: 		$mode='text';
1.257     albertel 1913: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1914: 		$mode='answer';
                   1915: 	    }
1.329     albertel 1916: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1917: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1918: 	}
1.441     www      1919: 
1.44      ng       1920: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1921:         # if this subroutine has been called once.
1.41      ng       1922: 	my %keyhash = ();
1.257     albertel 1923: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1924: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1925: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1926: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1927: 
1.257     albertel 1928: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1929: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1930: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1931: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1932: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1933: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1934: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1935: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1936: 	}
1.257     albertel 1937: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1938: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1939: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1940: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1941: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1942: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1943: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1944: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1945: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1946: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1947: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1948: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1949: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1950: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1951: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1952: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1953: 			&build_section_inputs().
1.326     albertel 1954: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1955: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1956: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1957: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1958: 	if ($env{'form.handgrade'} eq 'yes') {
                   1959: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1960: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1961: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1962: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1963: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1964: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1965: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1966: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1967: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1968: 	    }
1.123     ng       1969: 	}
1.41      ng       1970: 	
                   1971: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1972: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1973: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1974: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1975: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1976: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1977: 		'" />'."\n".
                   1978: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1979: 	    $cts++;
                   1980: 	}
                   1981: 	$request->print($prnmsg);
1.32      ng       1982: 
1.257     albertel 1983: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1984: #
                   1985: # Print out the keyword options line
                   1986: #
1.41      ng       1987: 	    $request->print(<<KEYWORDS);
1.38      ng       1988: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1989: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1990: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1991:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1992: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1993: KEYWORDS
1.88      www      1994: #
                   1995: # Load the other essays for similarity check
                   1996: #
1.324     albertel 1997:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1998: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1999: 	    $apath=&escape($apath);
1.88      www      2000: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2001: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2002:         }
                   2003:     }
1.44      ng       2004: 
1.441     www      2005: # This is where output for one specific student would start
1.468     albertel 2006:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2007:     $request->print("\n\n".
1.468     albertel 2008:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2009: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2010: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2011: 
1.257     albertel 2012:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2013: 	my $mode;
1.257     albertel 2014: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2015: 	    $mode='both';
1.257     albertel 2016: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2017: 	    $mode='text';
1.257     albertel 2018: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2019: 	    $mode='answer';
                   2020: 	}
1.329     albertel 2021: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2022: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2023:     }
1.144     albertel 2024: 
1.257     albertel 2025:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2026:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2027: 
1.44      ng       2028:     # Display student info
1.41      ng       2029:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2030:     my $result='<div class="LC_grade_submissions">';
                   2031:     
                   2032:     $result.='<div class="LC_grade_submissions_header">';
                   2033:     $result.= &mt('Submissions');
1.45      ng       2034:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2035: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2036:     if ($env{'form.handgrade'} eq 'no') {
                   2037: 	$result.='<span class="LC_grade_check_note">'.
                   2038: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2039: 
                   2040:     }
                   2041: 
                   2042: 
1.41      ng       2043: 
1.118     ng       2044:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2045:     my $fullname;
                   2046:     my $col_fullnames = [];
1.257     albertel 2047:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2048: 	(my $sub_result,$fullname,$col_fullnames)=
                   2049: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2050: 				 $counter);
                   2051: 	$result.=$sub_result;
1.41      ng       2052:     }
1.44      ng       2053:     $request->print($result."\n");
1.468     albertel 2054:     $request->print('</div>'."\n");
1.44      ng       2055:     # print student answer/submission
                   2056:     # Options are (1) Handgaded submission only
                   2057:     #             (2) Last submission, includes submission that is not handgraded 
                   2058:     #                  (for multi-response type part)
                   2059:     #             (3) Last submission plus the parts info
                   2060:     #             (4) The whole record for this student
1.257     albertel 2061:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2062: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2063: 	
                   2064: 	my $lastsubonly;
                   2065: 
1.151     albertel 2066: 	if ($$timestamp eq '') {
1.468     albertel 2067: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2068: 	} else {
1.468     albertel 2069: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2070: 
1.151     albertel 2071: 	    my %seenparts;
1.375     albertel 2072: 	    my @part_response_id = &flatten_responseType($responseType);
                   2073: 	    foreach my $part (@part_response_id) {
1.393     albertel 2074: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2075: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2076: 
1.375     albertel 2077: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2078: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2079: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2080: 		    if (exists($seenparts{$partid})) { next; }
                   2081: 		    $seenparts{$partid}=1;
1.207     albertel 2082: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2083: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2084: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2085: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2086: 			'\');" target="_self">'.
1.257     albertel 2087: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2088: 		    $request->print($submitby);
                   2089: 		    next;
                   2090: 		}
                   2091: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2092: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2093: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2094: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2095: 			' )</span>&nbsp; &nbsp;'.
1.468     albertel 2096: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2097: 		    next;
                   2098: 		}
1.468     albertel 2099: 		foreach my $submission (@$string) {
                   2100: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2101: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2102: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2103: 		    # Similarity check
                   2104: 		    my $similar='';
1.257     albertel 2105: 		    if($env{'form.checkPlag'}){
1.151     albertel 2106: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2107: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2108: 			if ($osim) {
                   2109: 			    $osim=int($osim*100.0);
1.426     albertel 2110: 			    my %old_course_desc = 
                   2111: 				&Apache::lonnet::coursedescription($ocrsid,
                   2112: 								   {'one_time' => 1});
                   2113: 
                   2114: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2115: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2116: 				    $osim,
                   2117: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2118: 				    $oname,$odom,
1.426     albertel 2119: 				    $old_course_desc{'description'},
1.427     albertel 2120: 				    $old_course_desc{'num'},
1.426     albertel 2121: 				    $old_course_desc{'domain'}).
1.398     albertel 2122: 				'</span></h3><blockquote><i>'.
1.151     albertel 2123: 				&keywords_highlight($oessay).
                   2124: 				'</i></blockquote><hr />';
                   2125: 			}
1.150     albertel 2126: 		    }
1.151     albertel 2127: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2128: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2129: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2130: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2131: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2132: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2133: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2134: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2135: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2136: 			if (@$files) {
1.468     albertel 2137: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2138: 			    my $file_counter = 0;
1.313     banghart 2139: 			    foreach my $file (@$files) {
1.468     albertel 2140: 			        $file_counter++;
1.232     albertel 2141: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2142: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2143: 			    }
1.236     albertel 2144: 			    $lastsubonly.='<br />';
1.41      ng       2145: 			}
1.468     albertel 2146: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2147: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2148: 					 $respid,\%record,$order);
                   2149: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2150: 			$lastsubonly.='</div>';
1.41      ng       2151: 		    }
                   2152: 		}
                   2153: 	    }
1.468     albertel 2154: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2155: 	}
                   2156: 	$request->print($lastsubonly);
1.468     albertel 2157:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2158: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2159: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2160:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2161: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2162: 								 $env{'request.course.id'},
1.44      ng       2163: 								 $last,'.submission',
                   2164: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2165:     }
1.120     ng       2166: 
1.121     ng       2167:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2168: 	.$udom.'" />'."\n");
1.44      ng       2169:     # return if view submission with no grading option
1.257     albertel 2170:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2171: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2172: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2173: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2174: 	$toGrade.='</div>'."\n";
1.257     albertel 2175: 	if (($env{'form.command'} eq 'submission') || 
                   2176: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2177: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2178: 	}
1.180     albertel 2179: 	$request->print($toGrade);
1.41      ng       2180: 	return;
1.180     albertel 2181:     } else {
1.468     albertel 2182: 	$request->print('</div>'."\n");
1.41      ng       2183:     }
1.33      ng       2184: 
1.121     ng       2185:     # essay grading message center
1.257     albertel 2186:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2187: 	my $result='<div class="LC_grade_message_center">';
                   2188:     
                   2189: 	$result.='<div class="LC_grade_message_center_header">'.
                   2190: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2191: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2192: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2193: 	if (scalar(@$col_fullnames) > 0) {
                   2194: 	    my $lastone = pop(@$col_fullnames);
                   2195: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2196: 	}
                   2197: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2198: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2199: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2200: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2201: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2202: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2203: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2204: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2205: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2206: 	    '<br />&nbsp;('.
1.468     albertel 2207: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2208: 	$result.='</div></div>';
1.121     ng       2209: 	$request->print($result);
1.118     ng       2210:     }
1.41      ng       2211: 
                   2212:     my %seen = ();
                   2213:     my @partlist;
1.129     ng       2214:     my @gradePartRespid;
1.375     albertel 2215:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2216:     $request->print('<div class="LC_grade_assign">'.
                   2217: 		    
                   2218: 		    '<div class="LC_grade_assign_header">'.
                   2219: 		    &mt('Assign Grades').'</div>'.
                   2220: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2221:     foreach my $part_response_id (@part_response_id) {
                   2222:     	my ($partid,$respid) = @{ $part_response_id };
                   2223: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2224: 	next if ($seen{$partid} > 0);
1.41      ng       2225: 	$seen{$partid}++;
1.393     albertel 2226: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2227: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2228: 	push @partlist,$partid;
1.129     ng       2229: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2230: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2231:     }
1.468     albertel 2232:     $request->print('</div></div>');
                   2233: 
                   2234:     $request->print('<div class="LC_grade_info_links">');
                   2235:     if ($perm{'vgr'}) {
                   2236: 	$request->print(
                   2237: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2238: 						   $uname,$udom,'check'));
                   2239:     }
                   2240:     if ($perm{'opa'}) {
                   2241: 	$request->print(
                   2242: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2243: 					 $uname,$udom,$symb,'check'));
                   2244:     }
                   2245:     $request->print('</div>');
                   2246: 
1.45      ng       2247:     $result='<input type="hidden" name="partlist'.$counter.
                   2248: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2249:     $result.='<input type="hidden" name="gradePartRespid'.
                   2250: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2251:     my $ctr = 0;
                   2252:     while ($ctr < scalar(@partlist)) {
                   2253: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2254: 	    $partlist[$ctr].'" />'."\n";
                   2255: 	$ctr++;
                   2256:     }
1.468     albertel 2257:     $request->print($result.''."\n");
1.41      ng       2258: 
1.441     www      2259: # Done with printing info for one student
                   2260: 
1.468     albertel 2261:     $request->print('</div>');#LC_grade_show_user_body
                   2262:     $request->print('</div>');#LC_grade_show_user
1.441     www      2263: 
                   2264: 
1.41      ng       2265:     # print end of form
                   2266:     if ($counter == $total) {
1.297     www      2267: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2268: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2269: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2270: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2271: 	my $ntstu ='<select name="NTSTU">'.
                   2272: 	    '<option>1</option><option>2</option>'.
                   2273: 	    '<option>3</option><option>5</option>'.
                   2274: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2275: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2276: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.485     albertel 2277: 	$endform.=&mt('[_1]student(s)',$ntstu);
                   2278: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2279: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2280: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2281: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2282: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2283:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2284:             "' name='increment' />";
1.485     albertel 2285: 	$endform.='</td></tr></table></form>';
1.324     albertel 2286: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2287: 	$request->print($endform);
                   2288:     }
                   2289:     return '';
1.38      ng       2290: }
                   2291: 
1.464     albertel 2292: sub check_collaborators {
                   2293:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2294:     my ($result,@col_fullnames);
                   2295:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2296:     foreach my $part (keys(%$handgrade)) {
                   2297: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2298: 					'.maxcollaborators',
                   2299: 					$symb,$udom,$uname);
                   2300: 	next if ($ncol <= 0);
                   2301: 	$part =~ s/\_/\./g;
                   2302: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2303: 	my (@good_collaborators, @bad_collaborators);
                   2304: 	foreach my $possible_collaborator
                   2305: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2306: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2307: 	    next if ($possible_collaborator eq '');
                   2308: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2309: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2310: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2311: 	    # Doing this grep allows 'fuzzy' specification
                   2312: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2313: 			       keys(%$classlist));
                   2314: 	    if (! scalar(@matches)) {
                   2315: 		push(@bad_collaborators, $possible_collaborator);
                   2316: 	    } else {
                   2317: 		push(@good_collaborators, @matches);
                   2318: 	    }
                   2319: 	}
                   2320: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2321: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2322: 	    foreach my $name (@good_collaborators) {
                   2323: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2324: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2325: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2326: 	    }
                   2327: 	    $result.='<br />'."\n";
1.466     albertel 2328: 	    my ($part)=split(/\./,$part);
1.464     albertel 2329: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2330: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2331: 		"\n";
                   2332: 	}
                   2333: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2334: 	    $result.='<div class="LC_warning">';
1.464     albertel 2335: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2336: 	    $result .= '</div>';
                   2337: 	}         
                   2338: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2339: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2340: 	    $result .= &mt('This student has submitted too many '.
                   2341: 		'collaborators.  Maximum is [_1].',$ncol);
                   2342: 	    $result .= '</div>';
                   2343: 	}
                   2344:     }
                   2345:     return ($result,$fullname,\@col_fullnames);
                   2346: }
                   2347: 
1.44      ng       2348: #--- Retrieve the last submission for all the parts
1.38      ng       2349: sub get_last_submission {
1.119     ng       2350:     my ($returnhash)=@_;
1.46      ng       2351:     my (@string,$timestamp);
1.119     ng       2352:     if ($$returnhash{'version'}) {
1.46      ng       2353: 	my %lasthash=();
                   2354: 	my ($version);
1.119     ng       2355: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2356: 	    foreach my $key (sort(split(/\:/,
                   2357: 					$$returnhash{$version.':keys'}))) {
                   2358: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2359: 		$timestamp = 
                   2360: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2361: 	    }
                   2362: 	}
1.397     albertel 2363: 	foreach my $key (keys(%lasthash)) {
                   2364: 	    next if ($key !~ /\.submission$/);
                   2365: 
                   2366: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2367: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2368: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2369: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2370: 	}
                   2371:     }
1.397     albertel 2372:     if (!@string) {
                   2373: 	$string[0] =
1.398     albertel 2374: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2375:     }
                   2376:     return (\@string,\$timestamp);
1.38      ng       2377: }
1.35      ng       2378: 
1.44      ng       2379: #--- High light keywords, with style choosen by user.
1.38      ng       2380: sub keywords_highlight {
1.44      ng       2381:     my $string    = shift;
1.257     albertel 2382:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2383:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2384:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2385:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2386:     foreach my $keyword (@keylist) {
                   2387: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2388:     }
                   2389:     return $string;
1.38      ng       2390: }
1.36      ng       2391: 
1.44      ng       2392: #--- Called from submission routine
1.38      ng       2393: sub processHandGrade {
1.41      ng       2394:     my ($request) = shift;
1.324     albertel 2395:     my $symb   = &get_symb($request);
                   2396:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2397:     my $button = $env{'form.gradeOpt'};
                   2398:     my $ngrade = $env{'form.NCT'};
                   2399:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2400:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2401:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2402: 
1.44      ng       2403:     if ($button eq 'Save & Next') {
                   2404: 	my $ctr = 0;
                   2405: 	while ($ctr < $ngrade) {
1.257     albertel 2406: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2407: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2408: 	    if ($errorflag eq 'no_score') {
                   2409: 		$ctr++;
                   2410: 		next;
                   2411: 	    }
1.104     albertel 2412: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2413: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2414: 		$ctr++;
                   2415: 		next;
                   2416: 	    }
1.257     albertel 2417: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2418: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2419: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2420:             my ($feedurl,$showsymb) =
                   2421: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2422: 	    my $messagetail;
1.62      albertel 2423: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2424: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2425: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2426: 		$subject.=' ['.$restitle.']';
1.44      ng       2427: 		my (@msgnum) = split(/,/,$includemsg);
                   2428: 		foreach (@msgnum) {
1.257     albertel 2429: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2430: 		}
1.80      ng       2431: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2432: 		if ($env{'form.withgrades'.$ctr}) {
                   2433: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2434: 		    $messagetail = " for <a href=\"".
1.418     albertel 2435: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2436: 		}
                   2437: 		$msgstatus = 
                   2438:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2439: 						     $message.$messagetail,
1.418     albertel 2440:                                                      undef,$feedurl,undef,
1.386     raeburn  2441:                                                      undef,undef,$showsymb,
                   2442:                                                      $restitle);
                   2443: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2444: 				$msgstatus);
1.44      ng       2445: 	    }
1.257     albertel 2446: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2447: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2448: 		foreach my $collabstr (@collabstrs) {
                   2449: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2450: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2451: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2452: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2453: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2454: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2455: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2456: 			    next;
1.418     albertel 2457: 			} elsif ($message ne '') {
                   2458: 			    my ($baseurl,$showsymb) = 
                   2459: 				&get_feedurl_and_symb($symb,$collaborator,
                   2460: 						      $udom);
                   2461: 			    if ($env{'form.withgrades'.$ctr}) {
                   2462: 				$messagetail = " for <a href=\"".
1.386     raeburn  2463:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2464: 			    }
1.418     albertel 2465: 			    $msgstatus = 
                   2466: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2467: 			}
1.44      ng       2468: 		    }
                   2469: 		}
                   2470: 	    }
                   2471: 	    $ctr++;
                   2472: 	}
                   2473:     }
                   2474: 
1.257     albertel 2475:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2476: 	# Keywords sorted in alphabatical order
1.257     albertel 2477: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2478: 	my %keyhash = ();
1.257     albertel 2479: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2480: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2481: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2482: 	$env{'form.keywords'} = join(' ',@keywords);
                   2483: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2484: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2485: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2486: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2487: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2488: 
                   2489: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2490: 	# New messages are saved in env for the next student.
1.119     ng       2491: 	# All messages are saved in nohist_handgrade.db
                   2492: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2493: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2494: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2495: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2496: 		$idx++;
                   2497: 	    }
                   2498: 	    $ctr++;
1.41      ng       2499: 	}
1.119     ng       2500: 	$ctr = 0;
                   2501: 	while ($ctr < $ngrade) {
1.257     albertel 2502: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2503: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2504: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2505: 		$idx++;
                   2506: 	    }
                   2507: 	    $ctr++;
1.41      ng       2508: 	}
1.257     albertel 2509: 	$env{'form.savemsgN'} = --$idx;
                   2510: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2511: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2512: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2513:     }
1.44      ng       2514:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2515:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2516:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2517: 	my ($ctr,$total) = (0,0);
                   2518: 	while ($ctr < $ngrade) {
1.257     albertel 2519: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2520: 	    $ctr++;
                   2521: 	}
1.257     albertel 2522: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2523: 	$ctr = 0;
                   2524: 	while ($ctr < $total) {
1.257     albertel 2525: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2526: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2527: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2528: 	    &submission($request,$ctr,$total-1);
1.41      ng       2529: 	    $ctr++;
                   2530: 	}
                   2531: 	return '';
                   2532:     }
1.36      ng       2533: 
1.121     ng       2534: # Go directly to grade student - from submission or link from chart page
1.120     ng       2535:     if ($button eq 'Grade Student') {
1.324     albertel 2536: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2537: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2538: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2539: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2540: 	&submission($request,0,0);
                   2541: 	return '';
                   2542:     }
                   2543: 
1.44      ng       2544:     # Get the next/previous one or group of students
1.257     albertel 2545:     my $firststu = $env{'form.unamedom0'};
                   2546:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2547:     my $ctr = 2;
1.41      ng       2548:     while ($laststu eq '') {
1.257     albertel 2549: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2550: 	$ctr++;
                   2551: 	$laststu = $firststu if ($ctr > $ngrade);
                   2552:     }
1.44      ng       2553: 
1.41      ng       2554:     my (@parsedlist,@nextlist);
                   2555:     my ($nextflg) = 0;
1.294     albertel 2556:     foreach (sort 
                   2557: 	     {
                   2558: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2559: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2560: 		 }
                   2561: 		 return $a cmp $b;
                   2562: 	     } (keys(%$fullname))) {
1.41      ng       2563: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2564: 	    push @parsedlist,$_;
                   2565: 	}
                   2566: 	$nextflg = 1 if ($_ eq $laststu);
                   2567: 	if ($button eq 'Previous') {
                   2568: 	    last if ($_ eq $firststu);
                   2569: 	    push @parsedlist,$_;
                   2570: 	}
                   2571:     }
                   2572:     $ctr = 0;
                   2573:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2574:     my ($partlist) = &response_type($symb);
1.41      ng       2575:     foreach my $student (@parsedlist) {
1.257     albertel 2576: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2577: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2578: 	
                   2579: 	if ($submitonly eq 'queued') {
                   2580: 	    my %queue_status = 
                   2581: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2582: 							$udom,$uname);
                   2583: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2584: 	}
                   2585: 
1.156     albertel 2586: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2587: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2588: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2589: 	    my $submitted = 0;
1.248     albertel 2590: 	    my $ungraded = 0;
                   2591: 	    my $incorrect = 0;
1.145     albertel 2592: 	    foreach (keys(%status)) {
                   2593: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2594: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2595: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2596: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2597: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2598: 		    $submitted = 0;
                   2599: 		}
1.41      ng       2600: 	    }
1.156     albertel 2601: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2602: 				     $submitonly eq 'incorrect' ||
                   2603: 				     $submitonly eq 'graded'));
1.248     albertel 2604: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2605: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2606: 	}
                   2607: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2608: 	last if ($ctr == $ntstu);
1.41      ng       2609: 	$ctr++;
                   2610:     }
1.36      ng       2611: 
1.41      ng       2612:     $ctr = 0;
                   2613:     my $total = scalar(@nextlist)-1;
1.39      ng       2614: 
1.41      ng       2615:     foreach (sort @nextlist) {
                   2616: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2617: 	$env{'form.student'}  = $uname;
                   2618: 	$env{'form.userdom'}  = $udom;
                   2619: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2620: 	&submission($request,$ctr,$total);
                   2621: 	$ctr++;
                   2622:     }
                   2623:     if ($total < 0) {
1.485     albertel 2624: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2625: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2626: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2627: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2628: 	$request->print($the_end);
                   2629:     }
                   2630:     return '';
1.38      ng       2631: }
1.36      ng       2632: 
1.44      ng       2633: #---- Save the score and award for each student, if changed
1.38      ng       2634: sub saveHandGrade {
1.324     albertel 2635:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2636:     my @version_parts;
1.104     albertel 2637:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2638: 					   $env{'request.course.id'});
1.104     albertel 2639:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2640:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2641:     my @parts_graded;
1.77      ng       2642:     my %newrecord  = ();
                   2643:     my ($pts,$wgt) = ('','');
1.269     raeburn  2644:     my %aggregate = ();
                   2645:     my $aggregateflag = 0;
1.301     albertel 2646:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2647:     foreach my $new_part (@parts) {
1.337     banghart 2648: 	#collaborator ($submi may vary for different parts
1.259     banghart 2649: 	if ($submitter && $new_part ne $part) { next; }
                   2650: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2651: 	if ($dropMenu eq 'excused') {
1.259     banghart 2652: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2653: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2654: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2655: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2656: 		}
1.364     banghart 2657: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2658: 	    }
1.125     ng       2659: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2660: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2661: 	    foreach my $key (keys (%record)) {
1.259     banghart 2662: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2663: 	    }
1.259     banghart 2664: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2665: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2666:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2667: 
                   2668:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2669: 					       [$new_part]);
                   2670:             my $aggtries =$totaltries;
1.269     raeburn  2671:             if ($last_resets{$new_part}) {
1.270     albertel 2672:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2673: 					   $new_part);
1.269     raeburn  2674:             }
1.270     albertel 2675: 
                   2676:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2677:             if ($aggtries > 0) {
1.327     albertel 2678:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2679:                 $aggregateflag = 1;
                   2680:             }
1.125     ng       2681: 	} elsif ($dropMenu eq '') {
1.259     banghart 2682: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2683: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2684: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2685: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2686: 		next;
                   2687: 	    }
1.259     banghart 2688: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2689: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2690: 	    my $partial= $pts/$wgt;
1.259     banghart 2691: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2692: 		#do not update score for part if not changed.
1.346     banghart 2693:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2694: 		next;
1.251     banghart 2695: 	    } else {
1.259     banghart 2696: 	        push @parts_graded, $new_part;
1.153     albertel 2697: 	    }
1.259     banghart 2698: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2699: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2700: 	    }
1.259     banghart 2701: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2702: 	    if ($partial == 0) {
1.153     albertel 2703: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2704: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2705: 		}
1.41      ng       2706: 	    } else {
1.153     albertel 2707: 		if ($record{$reckey} ne 'correct_by_override') {
                   2708: 		    $newrecord{$reckey} = 'correct_by_override';
                   2709: 		}
                   2710: 	    }	    
                   2711: 	    if ($submitter && 
1.259     banghart 2712: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2713: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2714: 	    }
1.259     banghart 2715: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2716: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2717: 	}
1.259     banghart 2718: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2719: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2720: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2721: 	        $dropMenu eq 'reset status')
                   2722: 	   {
1.342     banghart 2723: 	    push (@version_parts,$new_part);
1.259     banghart 2724: 	}
1.41      ng       2725:     }
1.301     albertel 2726:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2727:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2728: 
1.344     albertel 2729:     if (%newrecord) {
                   2730:         if (@version_parts) {
1.364     banghart 2731:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2732:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2733: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2734: 	    foreach my $new_part (@version_parts) {
                   2735: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2736: 				$new_part,\%newrecord);
                   2737: 	    }
1.259     banghart 2738:         }
1.44      ng       2739: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2740: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2741: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2742: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2743:     }
1.269     raeburn  2744:     if ($aggregateflag) {
                   2745:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2746: 			      $cdom,$cnum);
1.269     raeburn  2747:     }
1.301     albertel 2748:     return ('',$pts,$wgt);
1.36      ng       2749: }
1.322     albertel 2750: 
1.380     albertel 2751: sub check_and_remove_from_queue {
                   2752:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2753:     my @ungraded_parts;
                   2754:     foreach my $part (@{$parts}) {
                   2755: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2756: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2757: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2758: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2759: 		) {
                   2760: 	    push(@ungraded_parts, $part);
                   2761: 	}
                   2762:     }
                   2763:     if ( !@ungraded_parts ) {
                   2764: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2765: 					       $cnum,$domain,$stuname);
                   2766:     }
                   2767: }
                   2768: 
1.337     banghart 2769: sub handback_files {
                   2770:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2771:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2772:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2773: 
                   2774:     my @part_response_id = &flatten_responseType($responseType);
                   2775:     foreach my $part_response_id (@part_response_id) {
                   2776:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2777: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2778:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2779:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2780:                 my $file_counter = 1;
1.367     albertel 2781: 		my $file_msg;
1.337     banghart 2782:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2783:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2784:                     my ($directory,$answer_file) = 
                   2785:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2786:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2787: 		        &file_name_version_ext($answer_file);
1.355     banghart 2788: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2789: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2790: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2791:                     # fix file name
                   2792:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2793:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2794:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2795:             	                                $save_file_name);
1.337     banghart 2796:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2797:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2798:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2799:                     } else {
1.360     banghart 2800:                         # mark the file as read only
                   2801:                         my @files = ($save_file_name);
1.372     albertel 2802:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2803:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2804: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2805: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2806: 			}
                   2807:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2808: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2809: 
1.337     banghart 2810:                     }
                   2811:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2812:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2813:                     $file_counter++;
                   2814:                 }
1.367     albertel 2815: 		my $subject = "File Handed Back by Instructor ";
                   2816: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2817: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2818: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2819: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2820: 		my ($feedurl,$showsymb) = 
                   2821: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2822:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2823: 		my $msgstatus = 
                   2824:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2825: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2826:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2827:             }
                   2828:         }
1.338     banghart 2829:     return;
1.337     banghart 2830: }
                   2831: 
1.418     albertel 2832: sub get_feedurl_and_symb {
                   2833:     my ($symb,$uname,$udom) = @_;
                   2834:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2835:     $url = &Apache::lonnet::clutter($url);
                   2836:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2837: 					$symb,$udom,$uname);
                   2838:     if ($encrypturl =~ /^yes$/i) {
                   2839: 	&Apache::lonenc::encrypted(\$url,1);
                   2840: 	&Apache::lonenc::encrypted(\$symb,1);
                   2841:     }
                   2842:     return ($url,$symb);
                   2843: }
                   2844: 
1.313     banghart 2845: sub get_submitted_files {
                   2846:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2847:     my @files;
                   2848:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2849:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2850:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2851:     	    push(@files,$file_url.$file);
                   2852:         }
                   2853:     }
                   2854:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2855:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2856:     }
                   2857:     return (\@files);
                   2858: }
1.322     albertel 2859: 
1.269     raeburn  2860: # ----------- Provides number of tries since last reset.
                   2861: sub get_num_tries {
                   2862:     my ($record,$last_reset,$part) = @_;
                   2863:     my $timestamp = '';
                   2864:     my $num_tries = 0;
                   2865:     if ($$record{'version'}) {
                   2866:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2867:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2868:                 $timestamp = $$record{$version.':timestamp'};
                   2869:                 if ($timestamp > $last_reset) {
                   2870:                     $num_tries ++;
                   2871:                 } else {
                   2872:                     last;
                   2873:                 }
                   2874:             }
                   2875:         }
                   2876:     }
                   2877:     return $num_tries;
                   2878: }
                   2879: 
                   2880: # ----------- Determine decrements required in aggregate totals 
                   2881: sub decrement_aggs {
                   2882:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2883:     my %decrement = (
                   2884:                         attempts => 0,
                   2885:                         users => 0,
                   2886:                         correct => 0
                   2887:                     );
                   2888:     $decrement{'attempts'} = $aggtries;
                   2889:     if ($solvedstatus =~ /^correct/) {
                   2890:         $decrement{'correct'} = 1;
                   2891:     }
                   2892:     if ($aggtries == $totaltries) {
                   2893:         $decrement{'users'} = 1;
                   2894:     }
                   2895:     foreach my $type (keys (%decrement)) {
                   2896:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2897:     }
                   2898:     return;
                   2899: }
                   2900: 
                   2901: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2902: sub get_last_resets {
1.270     albertel 2903:     my ($symb,$courseid,$partids) =@_;
                   2904:     my %last_resets;
1.269     raeburn  2905:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2906:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2907:     my @keys;
                   2908:     foreach my $part (@{$partids}) {
                   2909: 	push(@keys,"$symb\0$part\0resettime");
                   2910:     }
                   2911:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2912: 				     $cdom,$cname);
                   2913:     foreach my $part (@{$partids}) {
                   2914: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2915:     }
1.270     albertel 2916:     return %last_resets;
1.269     raeburn  2917: }
                   2918: 
1.251     banghart 2919: # ----------- Handles creating versions for portfolio files as answers
                   2920: sub version_portfiles {
1.343     banghart 2921:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2922:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2923:     my @returned_keys;
1.255     banghart 2924:     my $parts = join('|', @$parts_graded);
1.359     www      2925:     my $portfolio_root = &propath($domain,$stu_name).
                   2926: 	'/userfiles/portfolio';
1.277     albertel 2927:     foreach my $key (keys(%$record)) {
1.259     banghart 2928:         my $new_portfiles;
1.263     banghart 2929:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2930:             my @versioned_portfiles;
1.367     albertel 2931:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2932:             foreach my $file (@portfiles) {
1.306     banghart 2933:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2934:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2935: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2936: 		    &file_name_version_ext($answer_file);
1.306     banghart 2937:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2938:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2939:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2940:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2941:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2942:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2943:                         [$directory.$new_answer],
1.306     banghart 2944:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2945:                 }
1.252     banghart 2946:             }
1.343     banghart 2947:             $$record{$key} = join(',',@versioned_portfiles);
                   2948:             push(@returned_keys,$key);
1.251     banghart 2949:         }
                   2950:     } 
1.343     banghart 2951:     return (@returned_keys);   
1.305     banghart 2952: }
                   2953: 
1.307     banghart 2954: sub get_next_version {
1.341     banghart 2955:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2956:     my $version;
                   2957:     foreach my $row (@$dir_list) {
                   2958:         my ($file) = split(/\&/,$row,2);
                   2959:         my ($file_name,$file_version,$file_ext) =
                   2960: 	    &file_name_version_ext($file);
                   2961:         if (($file_name eq $answer_name) && 
                   2962: 	    ($file_ext eq $answer_ext)) {
                   2963:                 # gets here if filename and extension match, regardless of version
                   2964:                 if ($file_version ne '') {
                   2965:                 # a versioned file is found  so save it for later
                   2966:                 if ($file_version > $version) {
                   2967: 		    $version = $file_version;
                   2968: 	        }
                   2969:             }
                   2970:         }
                   2971:     } 
                   2972:     $version ++;
                   2973:     return($version);
                   2974: }
                   2975: 
1.305     banghart 2976: sub version_selected_portfile {
1.306     banghart 2977:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2978:     my ($answer_name,$answer_ver,$answer_ext) =
                   2979:         &file_name_version_ext($file_name);
                   2980:     my $new_answer;
                   2981:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2982:     if($env{'form.copy'} eq '-1') {
                   2983:         $new_answer = 'problem getting file';
                   2984:     } else {
                   2985:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2986:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2987:                             $stu_name,$domain,'copy',
                   2988: 		        '/portfolio'.$directory.$new_answer);
                   2989:     }    
                   2990:     return ($new_answer);
1.251     banghart 2991: }
                   2992: 
1.304     albertel 2993: sub file_name_version_ext {
                   2994:     my ($file)=@_;
                   2995:     my @file_parts = split(/\./, $file);
                   2996:     my ($name,$version,$ext);
                   2997:     if (@file_parts > 1) {
                   2998: 	$ext=pop(@file_parts);
                   2999: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3000: 	    $version=pop(@file_parts);
                   3001: 	}
                   3002: 	$name=join('.',@file_parts);
                   3003:     } else {
                   3004: 	$name=join('.',@file_parts);
                   3005:     }
                   3006:     return($name,$version,$ext);
                   3007: }
                   3008: 
1.44      ng       3009: #--------------------------------------------------------------------------------------
                   3010: #
                   3011: #-------------------------- Next few routines handles grading by section or whole class
                   3012: #
                   3013: #--- Javascript to handle grading by section or whole class
1.42      ng       3014: sub viewgrades_js {
                   3015:     my ($request) = shift;
                   3016: 
1.41      ng       3017:     $request->print(<<VIEWJAVASCRIPT);
                   3018: <script type="text/javascript" language="javascript">
1.45      ng       3019:    function writePoint(partid,weight,point) {
1.125     ng       3020: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3021: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3022: 	if (point == "textval") {
1.125     ng       3023: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3024: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   3025: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       3026: 		var resetbox = false;
                   3027: 		for (var i=0; i<radioButton.length; i++) {
                   3028: 		    if (radioButton[i].checked) {
                   3029: 			textbox.value = i;
                   3030: 			resetbox = true;
                   3031: 		    }
                   3032: 		}
                   3033: 		if (!resetbox) {
                   3034: 		    textbox.value = "";
                   3035: 		}
                   3036: 		return;
                   3037: 	    }
1.109     matthew  3038: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3039: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3040: 				   ") greater than the weight for the part. Accept?");
                   3041: 		if (resp == false) {
                   3042: 		    textbox.value = "";
                   3043: 		    return;
                   3044: 		}
                   3045: 	    }
1.42      ng       3046: 	    for (var i=0; i<radioButton.length; i++) {
                   3047: 		radioButton[i].checked=false;
1.109     matthew  3048: 		if (parseFloat(point) == i) {
1.42      ng       3049: 		    radioButton[i].checked=true;
                   3050: 		}
                   3051: 	    }
1.41      ng       3052: 
1.42      ng       3053: 	} else {
1.125     ng       3054: 	    textbox.value = parseFloat(point);
1.42      ng       3055: 	}
1.41      ng       3056: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3057: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3058: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3059: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3060: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3061: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3062: 	    if (saveval != "correct") {
                   3063: 		scorename.value = point;
1.43      ng       3064: 		if (selname[0].selected != true) {
                   3065: 		    selname[0].selected = true;
                   3066: 		}
1.42      ng       3067: 	    }
                   3068: 	}
1.125     ng       3069: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3070:     }
                   3071: 
                   3072:     function writeRadText(partid,weight) {
1.125     ng       3073: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3074: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3075:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3076: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3077: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3078: 	    for (var i=0; i<radioButton.length; i++) {
                   3079: 		radioButton[i].checked=false;
                   3080: 
                   3081: 	    }
                   3082: 	    textbox.value = "";
                   3083: 
                   3084: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3085: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3086: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3087: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3088: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3089: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3090: 		if ((saveval != "correct") || override) {
1.42      ng       3091: 		    scorename.value = "";
1.125     ng       3092: 		    if (selval[1].selected) {
                   3093: 			selname[1].selected = true;
                   3094: 		    } else {
                   3095: 			selname[2].selected = true;
                   3096: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3097: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3098: 		    }
1.42      ng       3099: 		}
                   3100: 	    }
1.43      ng       3101: 	} else {
                   3102: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3103: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3104: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3105: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3106: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3107: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3108: 		if ((saveval != "correct") || override) {
1.125     ng       3109: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3110: 		    selname[0].selected = true;
                   3111: 		}
                   3112: 	    }
                   3113: 	}	    
1.42      ng       3114:     }
                   3115: 
                   3116:     function changeSelect(partid,user) {
1.125     ng       3117: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3118: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3119: 	var point  = textbox.value;
1.125     ng       3120: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3121: 
1.109     matthew  3122: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3123: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3124: 	    textbox.value = "";
                   3125: 	    return;
                   3126: 	}
1.109     matthew  3127: 	if (parseFloat(point) > parseFloat(weight)) {
                   3128: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3129: 			       ") greater than the weight of the part. Accept?");
                   3130: 	    if (resp == false) {
                   3131: 		textbox.value = "";
                   3132: 		return;
                   3133: 	    }
                   3134: 	}
1.42      ng       3135: 	selval[0].selected = true;
                   3136:     }
                   3137: 
                   3138:     function changeOneScore(partid,user) {
1.125     ng       3139: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3140: 	if (selval[1].selected || selval[2].selected) {
                   3141: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3142: 	    if (selval[2].selected) {
                   3143: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3144: 	    }
1.269     raeburn  3145:         }
1.42      ng       3146:     }
                   3147: 
                   3148:     function resetEntry(numpart) {
                   3149: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3150: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3151: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3152: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3153: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3154: 	    for (var i=0; i<radioButton.length; i++) {
                   3155: 		radioButton[i].checked=false;
                   3156: 
                   3157: 	    }
                   3158: 	    textbox.value = "";
                   3159: 	    selval[0].selected = true;
                   3160: 
                   3161: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3162: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3163: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3164: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3165: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3166: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3167: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3168: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3169: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3170: 		if (saveselval == "excused") {
1.43      ng       3171: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3172: 		} else {
1.43      ng       3173: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3174: 		}
                   3175: 	    }
1.41      ng       3176: 	}
1.42      ng       3177:     }
                   3178: 
1.41      ng       3179: </script>
                   3180: VIEWJAVASCRIPT
1.42      ng       3181: }
                   3182: 
1.44      ng       3183: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3184: sub viewgrades {
                   3185:     my ($request) = shift;
                   3186:     &viewgrades_js($request);
1.41      ng       3187: 
1.324     albertel 3188:     my ($symb) = &get_symb($request);
1.168     albertel 3189:     #need to make sure we have the correct data for later EXT calls, 
                   3190:     #thus invalidate the cache
                   3191:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3192:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3193:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3194:     &Apache::lonnet::clear_EXT_cache_status();
                   3195: 
1.398     albertel 3196:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3197:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3198: 
                   3199:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3200:     $result.=&jscriptNform($symb);
1.41      ng       3201: 
1.44      ng       3202:     #beginning of class grading form
1.442     banghart 3203:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3204:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3205: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3206: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3207: 	&build_section_inputs().
1.257     albertel 3208: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3209: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3210: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3211: 
1.126     ng       3212:     my $sectionClass;
1.430     banghart 3213:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3214:     if ($env{'form.section'} eq 'all') {
1.485     albertel 3215: 	$sectionClass='Class';
1.257     albertel 3216:     } elsif ($env{'form.section'} eq 'none') {
1.485     albertel 3217: 	$sectionClass='Students in no Section';
1.52      albertel 3218:     } else {
1.485     albertel 3219: 	$sectionClass='Students in Section(s) [_1]';
1.52      albertel 3220:     }
1.485     albertel 3221:     $result.=
                   3222: 	'<h3>'.
                   3223: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
1.474     albertel 3224:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3225:     #radio buttons/text box for assigning points for a section or class.
                   3226:     #handles different parts of a problem
1.375     albertel 3227:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3228:     my %weight = ();
                   3229:     my $ctsparts = 0;
1.45      ng       3230:     my %seen = ();
1.375     albertel 3231:     my @part_response_id = &flatten_responseType($responseType);
                   3232:     foreach my $part_response_id (@part_response_id) {
                   3233:     	my ($partid,$respid) = @{ $part_response_id };
                   3234: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3235: 	next if $seen{$partid};
                   3236: 	$seen{$partid}++;
1.375     albertel 3237: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3238: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3239: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3240: 
1.324     albertel 3241: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3242: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3243: 	my $ctr = 0;
1.42      ng       3244: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3245: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3246: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3247: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3248: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3249: 	    $ctr++;
                   3250: 	}
1.485     albertel 3251: 	$radio.='</tr></table>';
                   3252: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3253: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3254: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3255: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.485     albertel 3256: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3257: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3258: 		$weight{$partid}.')"> '.
1.401     albertel 3259: 	    '<option selected="selected"> </option>'.
1.485     albertel 3260: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3261: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3262: 	    '</select></td>'.
                   3263:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3264: 	$line.='<input type="hidden" name="partid_'.
                   3265: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3266: 	$line.='<input type="hidden" name="weight_'.
                   3267: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3268: 
                   3269: 	$result.=
                   3270: 	    &Apache::loncommon::start_data_table_row()."\n".
                   3271: 	    &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).
                   3272: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3273: 	$ctsparts++;
1.41      ng       3274:     }
1.474     albertel 3275:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3276: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3277:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3278: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3279: 
1.44      ng       3280:     #table listing all the students in a section/class
                   3281:     #header of table
1.485     albertel 3282:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
                   3283: 			 $section_display).'</h3>';
1.474     albertel 3284:     $result.= &Apache::loncommon::start_data_table().
                   3285: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 3286: 	'<th>'.&mt('No.').'</th>'.
1.474     albertel 3287: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3288:     my (@parts) = sort(&getpartlist($symb));
                   3289:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3290:     my @partids = ();
1.41      ng       3291:     foreach my $part (@parts) {
                   3292: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3293: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3294: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3295: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3296:         push(@partids, $partid);
1.324     albertel 3297: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3298: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3299: 	    $result.='<th>'.
                   3300: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3301: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3302: 	    next;
1.485     albertel 3303: 	    
1.207     albertel 3304: 	} else {
1.485     albertel 3305: 	    if ($display =~ /Problem Status/) {
                   3306: 		my $grade_status_mt = &mt('Grade Status');
                   3307: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3308: 	    }
                   3309: 	    my $part_mt = &mt('Part:');
                   3310: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3311: 	}
1.485     albertel 3312: 
1.474     albertel 3313: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3314:     }
1.474     albertel 3315:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3316: 
1.270     albertel 3317:     my %last_resets = 
                   3318: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3319: 
1.41      ng       3320:     #get info for each student
1.44      ng       3321:     #list all the students - with points and grade status
1.257     albertel 3322:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3323:     my $ctr = 0;
1.294     albertel 3324:     foreach (sort 
                   3325: 	     {
                   3326: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3327: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3328: 		 }
                   3329: 		 return $a cmp $b;
                   3330: 	     } (keys(%$fullname))) {
1.126     ng       3331: 	$ctr++;
1.324     albertel 3332: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3333: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3334:     }
1.474     albertel 3335:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3336:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3337:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3338: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3339:     if (scalar(%$fullname) eq 0) {
                   3340: 	my $colspan=3+scalar(@parts);
1.433     banghart 3341: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3342:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3343: 	$result='<span class="LC_warning">'.
1.485     albertel 3344: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3345: 	        $section_display, $stu_status).
1.433     banghart 3346: 	    '</span>';
1.96      albertel 3347:     }
1.324     albertel 3348:     $result.=&show_grading_menu_form($symb);
1.41      ng       3349:     return $result;
                   3350: }
                   3351: 
1.44      ng       3352: #--- call by previous routine to display each student
1.41      ng       3353: sub viewstudentgrade {
1.324     albertel 3354:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3355:     my ($uname,$udom) = split(/:/,$student);
                   3356:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3357:     my %aggregates = (); 
1.474     albertel 3358:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3359: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3360: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3361: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3362: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3363: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3364:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3365:     foreach my $apart (@$parts) {
                   3366: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3367: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3368:         $result.='<td align="center">';
1.269     raeburn  3369:         my ($aggtries,$totaltries);
                   3370:         unless (exists($aggregates{$part})) {
1.270     albertel 3371: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3372: 
                   3373: 	    $aggtries = $totaltries;
1.269     raeburn  3374:             if ($$last_resets{$part}) {  
1.270     albertel 3375:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3376: 					   $part);
                   3377:             }
1.269     raeburn  3378:             $result.='<input type="hidden" name="'.
                   3379:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3380:             $result.='<input type="hidden" name="'.
                   3381:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3382:             $aggregates{$part} = 1;
                   3383:         }
1.41      ng       3384: 	if ($type eq 'awarded') {
1.320     albertel 3385: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3386: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3387: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3388: 	    $result.='<input type="text" name="'.
1.89      albertel 3389: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3390: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3391: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3392: 	} elsif ($type eq 'solved') {
                   3393: 	    my ($status,$foo)=split(/_/,$score,2);
                   3394: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3395: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3396: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3397: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3398: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3399: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3400: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3401: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3402: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3403: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3404: 	} else {
                   3405: 	    $result.='<input type="hidden" name="'.
                   3406: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3407: 		    "\n";
1.233     albertel 3408: 	    $result.='<input type="text" name="'.
1.122     ng       3409: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3410: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3411: 	}
                   3412:     }
1.474     albertel 3413:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3414:     return $result;
1.38      ng       3415: }
                   3416: 
1.44      ng       3417: #--- change scores for all the students in a section/class
                   3418: #    record does not get update if unchanged
1.38      ng       3419: sub editgrades {
1.41      ng       3420:     my ($request) = @_;
                   3421: 
1.324     albertel 3422:     my $symb=&get_symb($request);
1.433     banghart 3423:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3424:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3425:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3426:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3427: 
1.477     albertel 3428:     my $result= &Apache::loncommon::start_data_table().
                   3429: 	&Apache::loncommon::start_data_table_header_row().
                   3430: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3431: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3432:     my %scoreptr = (
                   3433: 		    'correct'  =>'correct_by_override',
                   3434: 		    'incorrect'=>'incorrect_by_override',
                   3435: 		    'excused'  =>'excused',
                   3436: 		    'ungraded' =>'ungraded_attempted',
                   3437: 		    'nothing'  => '',
                   3438: 		    );
1.257     albertel 3439:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3440: 
1.44      ng       3441:     my (@partid);
                   3442:     my %weight = ();
1.54      albertel 3443:     my %columns = ();
1.44      ng       3444:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3445: 
1.324     albertel 3446:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3447:     my $header;
1.257     albertel 3448:     while ($ctr < $env{'form.totalparts'}) {
                   3449: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3450: 	push @partid,$partid;
1.257     albertel 3451: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3452: 	$ctr++;
1.54      albertel 3453:     }
1.324     albertel 3454:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3455:     foreach my $partid (@partid) {
1.478     albertel 3456: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3457: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3458: 	$columns{$partid}=2;
                   3459: 	foreach my $stores (@parts) {
                   3460: 	    my ($part,$type) = &split_part_type($stores);
                   3461: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3462: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3463: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3464: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3465: 	    $display =~ s/Number of Attempts/Tries/;
1.478     albertel 3466: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
                   3467: 		'<th align="center">'.&mt('New '.$display).'</th>';
1.54      albertel 3468: 	    $columns{$partid}+=2;
                   3469: 	}
                   3470:     }
                   3471:     foreach my $partid (@partid) {
1.324     albertel 3472: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3473: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3474: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3475: 	    '</th>';
1.54      albertel 3476: 
1.44      ng       3477:     }
1.477     albertel 3478:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3479: 	&Apache::loncommon::start_data_table_header_row().
                   3480: 	$header.
                   3481: 	&Apache::loncommon::end_data_table_header_row();
                   3482:     my @noupdate;
1.126     ng       3483:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3484:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3485: 	my $line;
1.257     albertel 3486: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3487: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3488: 	my %newrecord;
                   3489: 	my $updateflag = 0;
1.281     albertel 3490: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3491: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3492: 	if (!&canmodify($usec)) {
1.126     ng       3493: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3494: 	    push(@noupdate,
1.478     albertel 3495: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3496: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3497: 	    next;
                   3498: 	}
1.269     raeburn  3499:         my %aggregate = ();
                   3500:         my $aggregateflag = 0;
1.281     albertel 3501: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3502: 	foreach (@partid) {
1.257     albertel 3503: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3504: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3505: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3506: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3507: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3508: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3509: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3510: 	    my $score;
                   3511: 	    if ($partial eq '') {
1.257     albertel 3512: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3513: 	    } elsif ($partial > 0) {
                   3514: 		$score = 'correct_by_override';
                   3515: 	    } elsif ($partial == 0) {
                   3516: 		$score = 'incorrect_by_override';
                   3517: 	    }
1.257     albertel 3518: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3519: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3520: 
1.292     albertel 3521: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3522: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3523: 	    if ($dropMenu eq 'reset status' &&
                   3524: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3525: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3526: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3527: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3528: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3529: 		$updateflag = 1;
1.269     raeburn  3530:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3531:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3532:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3533:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3534:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3535:                     $aggregateflag = 1;
                   3536:                 }
1.139     albertel 3537: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3538: 		$updateflag = 1;
                   3539: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3540: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3541: 		$rec_update++;
1.125     ng       3542: 	    }
                   3543: 
1.93      albertel 3544: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3545: 		'<td align="center">'.$awarded.
                   3546: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3547: 
1.54      albertel 3548: 
                   3549: 	    my $partid=$_;
                   3550: 	    foreach my $stores (@parts) {
                   3551: 		my ($part,$type) = &split_part_type($stores);
                   3552: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3553: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3554: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3555: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3556: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3557: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3558: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3559: 		    $updateflag=1;
                   3560: 		}
1.93      albertel 3561: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3562: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3563: 	    }
1.44      ng       3564: 	}
1.477     albertel 3565: 	$line.="\n";
1.301     albertel 3566: 
                   3567: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3568: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3569: 
1.44      ng       3570: 	if ($updateflag) {
                   3571: 	    $count++;
1.257     albertel 3572: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3573: 				    $udom,$uname);
1.301     albertel 3574: 
                   3575: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3576: 					      $cnum,$udom,$uname)) {
                   3577: 		# need to figure out if should be in queue.
                   3578: 		my %record =  
                   3579: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3580: 					     $udom,$uname);
                   3581: 		my $all_graded = 1;
                   3582: 		my $none_graded = 1;
                   3583: 		foreach my $part (@parts) {
                   3584: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3585: 			$all_graded = 0;
                   3586: 		    } else {
                   3587: 			$none_graded = 0;
                   3588: 		    }
                   3589: 		}
                   3590: 
                   3591: 		if ($all_graded || $none_graded) {
                   3592: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3593: 							   $symb,$cdom,$cnum,
                   3594: 							   $udom,$uname);
                   3595: 		}
                   3596: 	    }
                   3597: 
1.477     albertel 3598: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3599: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3600: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3601: 	    $updateCtr++;
1.93      albertel 3602: 	} else {
1.477     albertel 3603: 	    push(@noupdate,
                   3604: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3605: 	    $noupdateCtr++;
1.44      ng       3606: 	}
1.269     raeburn  3607:         if ($aggregateflag) {
                   3608:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3609: 				  $cdom,$cnum);
1.269     raeburn  3610:         }
1.93      albertel 3611:     }
1.477     albertel 3612:     if (@noupdate) {
1.126     ng       3613: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3614: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3615: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3616: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3617: 	    &mt('No Changes Occurred For the Students Below').
                   3618: 	    '</td>'.
1.477     albertel 3619: 	    &Apache::loncommon::end_data_table_row();
                   3620: 	foreach my $line (@noupdate) {
                   3621: 	    $result.=
                   3622: 		&Apache::loncommon::start_data_table_row().
                   3623: 		$line.
                   3624: 		&Apache::loncommon::end_data_table_row();
                   3625: 	}
1.44      ng       3626:     }
1.477     albertel 3627:     $result .= &Apache::loncommon::end_data_table().
                   3628: 	&show_grading_menu_form($symb);
1.478     albertel 3629:     my $msg = '<p><b>'.
                   3630: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3631: 	    $rec_update,$count).'</b><br />'.
                   3632: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3633: 	'</b></p>';
1.44      ng       3634:     return $title.$msg.$result;
1.5       albertel 3635: }
1.54      albertel 3636: 
                   3637: sub split_part_type {
                   3638:     my ($partstr) = @_;
                   3639:     my ($temp,@allparts)=split(/_/,$partstr);
                   3640:     my $type=pop(@allparts);
1.439     albertel 3641:     my $part=join('_',@allparts);
1.54      albertel 3642:     return ($part,$type);
                   3643: }
                   3644: 
1.44      ng       3645: #------------- end of section for handling grading by section/class ---------
                   3646: #
                   3647: #----------------------------------------------------------------------------
                   3648: 
1.5       albertel 3649: 
1.44      ng       3650: #----------------------------------------------------------------------------
                   3651: #
                   3652: #-------------------------- Next few routines handles grading by csv upload
                   3653: #
                   3654: #--- Javascript to handle csv upload
1.27      albertel 3655: sub csvupload_javascript_reverse_associate {
1.246     albertel 3656:     my $error1=&mt('You need to specify the username or ID');
                   3657:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3658:   return(<<ENDPICK);
                   3659:   function verify(vf) {
                   3660:     var foundsomething=0;
                   3661:     var founduname=0;
1.243     albertel 3662:     var foundID=0;
1.27      albertel 3663:     for (i=0;i<=vf.nfields.value;i++) {
                   3664:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3665:       if (i==0 && tw!=0) { foundID=1; }
                   3666:       if (i==1 && tw!=0) { founduname=1; }
                   3667:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3668:     }
1.246     albertel 3669:     if (founduname==0 && foundID==0) {
                   3670: 	alert('$error1');
                   3671: 	return;
1.27      albertel 3672:     }
                   3673:     if (foundsomething==0) {
1.246     albertel 3674: 	alert('$error2');
                   3675: 	return;
1.27      albertel 3676:     }
                   3677:     vf.submit();
                   3678:   }
                   3679:   function flip(vf,tf) {
                   3680:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3681:     var i;
                   3682:     for (i=0;i<=vf.nfields.value;i++) {
                   3683:       //can not pick the same destination field for both name and domain
                   3684:       if (((i ==0)||(i ==1)) && 
                   3685:           ((tf==0)||(tf==1)) && 
                   3686:           (i!=tf) &&
                   3687:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3688:         eval('vf.f'+i+'.selectedIndex=0;')
                   3689:       }
                   3690:     }
                   3691:   }
                   3692: ENDPICK
                   3693: }
                   3694: 
                   3695: sub csvupload_javascript_forward_associate {
1.246     albertel 3696:     my $error1=&mt('You need to specify the username or ID');
                   3697:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3698:   return(<<ENDPICK);
                   3699:   function verify(vf) {
                   3700:     var foundsomething=0;
                   3701:     var founduname=0;
1.243     albertel 3702:     var foundID=0;
1.27      albertel 3703:     for (i=0;i<=vf.nfields.value;i++) {
                   3704:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3705:       if (tw==1) { foundID=1; }
                   3706:       if (tw==2) { founduname=1; }
                   3707:       if (tw>3) { foundsomething=1; }
1.27      albertel 3708:     }
1.246     albertel 3709:     if (founduname==0 && foundID==0) {
                   3710: 	alert('$error1');
                   3711: 	return;
1.27      albertel 3712:     }
                   3713:     if (foundsomething==0) {
1.246     albertel 3714: 	alert('$error2');
                   3715: 	return;
1.27      albertel 3716:     }
                   3717:     vf.submit();
                   3718:   }
                   3719:   function flip(vf,tf) {
                   3720:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3721:     var i;
                   3722:     //can not pick the same destination field twice
                   3723:     for (i=0;i<=vf.nfields.value;i++) {
                   3724:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3725:         eval('vf.f'+i+'.selectedIndex=0;')
                   3726:       }
                   3727:     }
                   3728:   }
                   3729: ENDPICK
                   3730: }
                   3731: 
1.26      albertel 3732: sub csvuploadmap_header {
1.324     albertel 3733:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3734:     my $javascript;
1.257     albertel 3735:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3736: 	$javascript=&csvupload_javascript_reverse_associate();
                   3737:     } else {
                   3738: 	$javascript=&csvupload_javascript_forward_associate();
                   3739:     }
1.45      ng       3740: 
1.324     albertel 3741:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3742:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3743:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3744:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3745:     $request->print(<<ENDPICK);
1.26      albertel 3746: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3747: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3748: $result
1.326     albertel 3749: <hr />
1.26      albertel 3750: <h3>Identify fields</h3>
                   3751: Total number of records found in file: $distotal <hr />
                   3752: Enter as many fields as you can. The system will inform you and bring you back
                   3753: to this page if the data selected is insufficient to run your class.<hr />
                   3754: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3755: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3756: <input type="hidden" name="associate"  value="" />
                   3757: <input type="hidden" name="phase"      value="three" />
                   3758: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3759: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3760: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3761: <input type="hidden" name="upfile_associate" 
1.257     albertel 3762:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3763: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3764: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3765: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3766: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3767: <hr />
                   3768: <script type="text/javascript" language="Javascript">
                   3769: $javascript
                   3770: </script>
                   3771: ENDPICK
1.118     ng       3772:     return '';
1.26      albertel 3773: 
                   3774: }
                   3775: 
                   3776: sub csvupload_fields {
1.324     albertel 3777:     my ($symb) = @_;
                   3778:     my (@parts) = &getpartlist($symb);
1.243     albertel 3779:     my @fields=(['ID','Student ID'],
                   3780: 		['username','Student Username'],
                   3781: 		['domain','Student Domain']);
1.324     albertel 3782:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3783:     foreach my $part (sort(@parts)) {
                   3784: 	my @datum;
                   3785: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3786: 	my $name=$part;
                   3787: 	if  (!$display) { $display = $name; }
                   3788: 	@datum=($name,$display);
1.244     albertel 3789: 	if ($name=~/^stores_(.*)_awarded/) {
                   3790: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3791: 	}
1.41      ng       3792: 	push(@fields,\@datum);
                   3793:     }
                   3794:     return (@fields);
1.26      albertel 3795: }
                   3796: 
                   3797: sub csvuploadmap_footer {
1.41      ng       3798:     my ($request,$i,$keyfields) =@_;
                   3799:     $request->print(<<ENDPICK);
1.26      albertel 3800: </table>
                   3801: <input type="hidden" name="nfields" value="$i" />
                   3802: <input type="hidden" name="keyfields" value="$keyfields" />
                   3803: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3804: </form>
                   3805: ENDPICK
                   3806: }
                   3807: 
1.283     albertel 3808: sub checkforfile_js {
1.86      ng       3809:     my $result =<<CSVFORMJS;
                   3810: <script type="text/javascript" language="javascript">
                   3811:     function checkUpload(formname) {
                   3812: 	if (formname.upfile.value == "") {
                   3813: 	    alert("Please use the browse button to select a file from your local directory.");
                   3814: 	    return false;
                   3815: 	}
                   3816: 	formname.submit();
                   3817:     }
                   3818:     </script>
                   3819: CSVFORMJS
1.283     albertel 3820:     return $result;
                   3821: }
                   3822: 
                   3823: sub upcsvScores_form {
                   3824:     my ($request) = shift;
1.324     albertel 3825:     my ($symb)=&get_symb($request);
1.283     albertel 3826:     if (!$symb) {return '';}
                   3827:     my $result=&checkforfile_js();
1.257     albertel 3828:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3829:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3830:     $result.=$table;
1.326     albertel 3831:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3832:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3833:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3834: 	'.</b></td></tr>'."\n";
                   3835:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3836:     my $upload=&mt("Upload Scores");
1.86      ng       3837:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3838:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3839:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3840:     $result.=<<ENDUPFORM;
1.106     albertel 3841: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3842: <input type="hidden" name="symb" value="$symb" />
                   3843: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3844: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3845: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3846: $upfile_select
1.370     www      3847: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3848: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3849: </form>
                   3850: ENDUPFORM
1.370     www      3851:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3852:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3853:     .'</td></tr></table>'."\n";
1.86      ng       3854:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3855:     $result.=&show_grading_menu_form($symb);
1.86      ng       3856:     return $result;
                   3857: }
                   3858: 
                   3859: 
1.26      albertel 3860: sub csvuploadmap {
1.41      ng       3861:     my ($request)= @_;
1.324     albertel 3862:     my ($symb)=&get_symb($request);
1.41      ng       3863:     if (!$symb) {return '';}
1.72      ng       3864: 
1.41      ng       3865:     my $datatoken;
1.257     albertel 3866:     if (!$env{'form.datatoken'}) {
1.41      ng       3867: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3868:     } else {
1.257     albertel 3869: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3870: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3871:     }
1.41      ng       3872:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3873:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3874:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3875:     my ($i,$keyfields);
                   3876:     if (@records) {
1.324     albertel 3877: 	my @fields=&csvupload_fields($symb);
1.45      ng       3878: 
1.257     albertel 3879: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3880: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3881: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3882: 							  \@fields);
                   3883: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3884: 	    chop($keyfields);
                   3885: 	} else {
                   3886: 	    unshift(@fields,['none','']);
                   3887: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3888: 							    \@fields);
1.311     banghart 3889:             foreach my $rec (@records) {
                   3890:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3891:                 if (%temp) {
                   3892:                     $keyfields=join(',',sort(keys(%temp)));
                   3893:                     last;
                   3894:                 }
                   3895:             }
1.41      ng       3896: 	}
                   3897:     }
                   3898:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3899:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3900: 
1.41      ng       3901:     return '';
1.27      albertel 3902: }
                   3903: 
1.246     albertel 3904: sub csvuploadoptions {
1.41      ng       3905:     my ($request)= @_;
1.324     albertel 3906:     my ($symb)=&get_symb($request);
1.257     albertel 3907:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3908:     my $ignore=&mt('Ignore First Line');
                   3909:     $request->print(<<ENDPICK);
                   3910: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3911: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3912: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3913: <!--
1.246     albertel 3914: <p>
                   3915: <label>
                   3916:    <input type="checkbox" name="show_full_results" />
                   3917:    Show a table of all changes
                   3918: </label>
                   3919: </p>
1.302     albertel 3920: -->
1.246     albertel 3921: <p>
                   3922: <label>
                   3923:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3924:    Overwrite any existing score
                   3925: </label>
                   3926: </p>
                   3927: ENDPICK
                   3928:     my %fields=&get_fields();
                   3929:     if (!defined($fields{'domain'})) {
1.257     albertel 3930: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3931: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3932:     }
1.257     albertel 3933:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3934: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3935: 	my $cleankey=$1;
                   3936: 	if ($cleankey eq 'command') { next; }
                   3937: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3938: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3939:     }
                   3940:     # FIXME do a check for any duplicated user ids...
                   3941:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3942:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3943: <hr /></form>'."\n");
1.324     albertel 3944:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3945:     return '';
                   3946: }
                   3947: 
                   3948: sub get_fields {
                   3949:     my %fields;
1.257     albertel 3950:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3951:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3952: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3953: 	    if ($env{'form.f'.$i} ne 'none') {
                   3954: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3955: 	    }
                   3956: 	} else {
1.257     albertel 3957: 	    if ($env{'form.f'.$i} ne 'none') {
                   3958: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3959: 	    }
                   3960: 	}
1.27      albertel 3961:     }
1.246     albertel 3962:     return %fields;
                   3963: }
                   3964: 
                   3965: sub csvuploadassign {
                   3966:     my ($request)= @_;
1.324     albertel 3967:     my ($symb)=&get_symb($request);
1.246     albertel 3968:     if (!$symb) {return '';}
1.345     bowersj2 3969:     my $error_msg = '';
1.246     albertel 3970:     &Apache::loncommon::load_tmp_file($request);
                   3971:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3972:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3973:     my %fields=&get_fields();
1.41      ng       3974:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3975:     my $courseid=$env{'request.course.id'};
1.97      albertel 3976:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3977:     my @notallowed;
1.41      ng       3978:     my @skipped;
                   3979:     my $countdone=0;
                   3980:     foreach my $grade (@gradedata) {
                   3981: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3982: 	my $domain;
                   3983: 	if ($entries{$fields{'domain'}}) {
                   3984: 	    $domain=$entries{$fields{'domain'}};
                   3985: 	} else {
1.257     albertel 3986: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3987: 	}
1.243     albertel 3988: 	$domain=~s/\s//g;
1.41      ng       3989: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3990: 	$username=~s/\s//g;
1.243     albertel 3991: 	if (!$username) {
                   3992: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3993: 	    $id=~s/\s//g;
1.243     albertel 3994: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3995: 	    $username=$ids{$id};
                   3996: 	}
1.41      ng       3997: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3998: 	    my $id=$entries{$fields{'ID'}};
                   3999: 	    $id=~s/\s//g;
                   4000: 	    if ($id) {
                   4001: 		push(@skipped,"$id:$domain");
                   4002: 	    } else {
                   4003: 		push(@skipped,"$username:$domain");
                   4004: 	    }
1.41      ng       4005: 	    next;
                   4006: 	}
1.108     albertel 4007: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4008: 	if (!&canmodify($usec)) {
                   4009: 	    push(@notallowed,"$username:$domain");
                   4010: 	    next;
                   4011: 	}
1.244     albertel 4012: 	my %points;
1.41      ng       4013: 	my %grades;
                   4014: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4015: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4016: 		$dest eq 'domain') { next; }
                   4017: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4018: 	    if ($dest=~/stores_(.*)_points/) {
                   4019: 		my $part=$1;
                   4020: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4021: 					      $symb,$domain,$username);
1.345     bowersj2 4022:                 if ($wgt) {
                   4023:                     $entries{$fields{$dest}}=~s/\s//g;
                   4024:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4025:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4026:                                           : 'correct_by_override';
1.345     bowersj2 4027:                     $grades{"resource.$part.awarded"}=$pcr;
                   4028:                     $grades{"resource.$part.solved"}=$award;
                   4029:                     $points{$part}=1;
                   4030:                 } else {
                   4031:                     $error_msg = "<br />" .
                   4032:                         &mt("Some point values were assigned"
                   4033:                             ." for problems with a weight "
                   4034:                             ."of zero. These values were "
                   4035:                             ."ignored.");
                   4036:                 }
1.244     albertel 4037: 	    } else {
                   4038: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4039: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4040: 		my $store_key=$dest;
                   4041: 		$store_key=~s/^stores/resource/;
                   4042: 		$store_key=~s/_/\./g;
                   4043: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4044: 	    }
1.41      ng       4045: 	}
1.508     www      4046: 	if (! %grades) { 
                   4047:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4048:         } else {
                   4049: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4050: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4051: 					   $env{'request.course.id'},
                   4052: 					   $domain,$username);
1.508     www      4053: 	   if ($result eq 'ok') {
                   4054: 	      $request->print('.');
                   4055: 	   } else {
                   4056: 	      $request->print("<p><span class=\"LC_error\">".
                   4057:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4058:                                   "$username:$domain",$result)."</span></p>");
                   4059: 	   }
                   4060: 	   $request->rflush();
                   4061: 	   $countdone++;
                   4062:         }
1.41      ng       4063:     }
1.508     www      4064:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
1.41      ng       4065:     if (@skipped) {
1.508     www      4066: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
1.106     albertel 4067: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4068:     }
                   4069:     if (@notallowed) {
1.508     www      4070: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
1.106     albertel 4071: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4072:     }
1.106     albertel 4073:     $request->print("<br />\n");
1.324     albertel 4074:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4075:     return $error_msg;
1.26      albertel 4076: }
1.44      ng       4077: #------------- end of section for handling csv file upload ---------
                   4078: #
                   4079: #-------------------------------------------------------------------
                   4080: #
1.122     ng       4081: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4082: #
                   4083: #--- Select a page/sequence and a student to grade
1.68      ng       4084: sub pickStudentPage {
                   4085:     my ($request) = shift;
                   4086: 
                   4087:     $request->print(<<LISTJAVASCRIPT);
                   4088: <script type="text/javascript" language="javascript">
                   4089: 
                   4090: function checkPickOne(formname) {
1.76      ng       4091:     if (radioSelection(formname.student) == null) {
1.68      ng       4092: 	alert("Please select the student you wish to grade.");
                   4093: 	return;
                   4094:     }
1.125     ng       4095:     ptr = pullDownSelection(formname.selectpage);
                   4096:     formname.page.value = formname["page"+ptr].value;
                   4097:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4098:     formname.submit();
                   4099: }
                   4100: 
                   4101: </script>
                   4102: LISTJAVASCRIPT
1.118     ng       4103:     &commonJSfunctions($request);
1.324     albertel 4104:     my ($symb) = &get_symb($request);
1.257     albertel 4105:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4106:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4107:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4108: 
1.398     albertel 4109:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4110: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4111: 
1.80      ng       4112:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4113:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4114:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4115: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4116: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4117:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4118:     my $ctr=0;
1.68      ng       4119:     foreach (@$titles) {
                   4120: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4121: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4122: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4123: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4124: 	$ctr++;
1.68      ng       4125:     }
1.485     albertel 4126:     $select.= '</select>';
                   4127:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
                   4128: 
1.70      ng       4129:     $ctr=0;
                   4130:     foreach (@$titles) {
                   4131: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4132: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4133: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4134: 	$ctr++;
                   4135:     }
1.72      ng       4136:     $result.='<input type="hidden" name="page" />'."\n".
                   4137: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4138: 
1.485     albertel 4139:     my $options =
                   4140: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4141: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
                   4142:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
                   4143: 
                   4144:     $options =
                   4145: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4146: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4147: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
                   4148:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
1.432     banghart 4149:     
                   4150:     $result.=&build_section_inputs();
1.442     banghart 4151:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4152:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4153: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4154: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4155: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4156: 
1.485     albertel 4157:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
                   4158: 			  '<input type="text" name="CODE" value="" />').
                   4159: 			      '<br />'."\n";
1.382     albertel 4160: 
1.80      ng       4161:     $result.='&nbsp;<input type="button" '.
1.485     albertel 4162: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
1.72      ng       4163: 
1.68      ng       4164:     $request->print($result);
                   4165: 
1.485     albertel 4166:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4167: 	&Apache::loncommon::start_data_table().
                   4168: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4169: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4170: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4171: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4172: 	'<th>'.&nameUserString('header').'</th>'.
                   4173: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4174:  
1.76      ng       4175:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4176:     my $ptr = 1;
1.294     albertel 4177:     foreach my $student (sort 
                   4178: 			 {
                   4179: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4180: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4181: 			     }
                   4182: 			     return $a cmp $b;
                   4183: 			 } (keys(%$fullname))) {
1.68      ng       4184: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4185: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4186:                                   : '</td>');
1.126     ng       4187: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4188: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4189: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4190: 	$studentTable.=
                   4191: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4192:                          : '');
1.68      ng       4193: 	$ptr++;
                   4194:     }
1.484     albertel 4195:     if ($ptr%2 == 0) {
                   4196: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4197: 	    &Apache::loncommon::end_data_table_row();
                   4198:     }
                   4199:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4200:     $studentTable.='<input type="button" '.
1.485     albertel 4201: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.68      ng       4202: 
1.324     albertel 4203:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4204:     $request->print($studentTable);
                   4205: 
                   4206:     return '';
                   4207: }
                   4208: 
                   4209: sub getSymbMap {
1.132     bowersj2 4210:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4211: 
                   4212:     my %symbx = ();
                   4213:     my @titles = ();
1.117     bowersj2 4214:     my $minder = 0;
                   4215: 
                   4216:     # Gather every sequence that has problems.
1.240     albertel 4217:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4218: 					       1,0,1);
1.117     bowersj2 4219:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4220: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4221: 	    my $title = $minder.'.'.
                   4222: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4223: 	    push(@titles, $title); # minder in case two titles are identical
                   4224: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4225: 	    $minder++;
1.241     albertel 4226: 	}
1.68      ng       4227:     }
                   4228:     return \@titles,\%symbx;
                   4229: }
                   4230: 
1.72      ng       4231: #
                   4232: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4233: sub displayPage {
                   4234:     my ($request) = shift;
                   4235: 
1.324     albertel 4236:     my ($symb) = &get_symb($request);
1.257     albertel 4237:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4238:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4239:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4240:     my $pageTitle = $env{'form.page'};
1.103     albertel 4241:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4242:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4243:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4244: 
                   4245:     #need to make sure we have the correct data for later EXT calls, 
                   4246:     #thus invalidate the cache
                   4247:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4248:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4249:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4250:     &Apache::lonnet::clear_EXT_cache_status();
                   4251: 
1.103     albertel 4252:     if (!&canview($usec)) {
1.485     albertel 4253: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4254: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4255: 	return;
                   4256:     }
1.398     albertel 4257:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4258:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4259: 	'</h3>'."\n";
1.500     albertel 4260:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4261:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4262: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4263:     } else {
                   4264: 	delete($env{'form.CODE'});
                   4265:     }
1.71      ng       4266:     &sub_page_js($request);
                   4267:     $request->print($result);
                   4268: 
1.132     bowersj2 4269:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4270:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4271:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4272:     if (!$map) {
1.485     albertel 4273: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4274: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4275: 	return; 
                   4276:     }
1.68      ng       4277:     my $iterator = $navmap->getIterator($map->map_start(),
                   4278: 					$map->map_finish());
                   4279: 
1.71      ng       4280:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4281: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4282: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4283: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4284: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4285: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4286: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4287: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4288: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4289: 
1.382     albertel 4290:     if (defined($env{'form.CODE'})) {
                   4291: 	$studentTable.=
                   4292: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4293:     }
1.381     albertel 4294:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4295: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4296: 
1.485     albertel 4297:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4298: 	&Apache::loncommon::start_data_table().
                   4299: 	&Apache::loncommon::start_data_table_header_row().
                   4300: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4301: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4302: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4303: 
1.329     albertel 4304:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4305:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4306:     $iterator->next(); # skip the first BEGIN_MAP
                   4307:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4308:     while ($depth > 0) {
1.68      ng       4309:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4310:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4311: 
1.385     albertel 4312:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4313: 	    my $parts = $curRes->parts();
1.68      ng       4314:             my $title = $curRes->compTitle();
1.71      ng       4315: 	    my $symbx = $curRes->symb();
1.484     albertel 4316: 	    $studentTable.=
                   4317: 		&Apache::loncommon::start_data_table_row().
                   4318: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4319: 		(scalar(@{$parts}) == 1 ? '' 
                   4320: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4321: 							scalar(@{$parts}))
                   4322: 		 ).
                   4323: 		 '</td>';
1.71      ng       4324: 	    $studentTable.='<td valign="top">';
1.382     albertel 4325: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4326: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4327: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4328: 					     undef,'both',\%form);
1.71      ng       4329: 	    } else {
1.382     albertel 4330: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4331: 		$companswer =~ s|<form(.*?)>||g;
                   4332: 		$companswer =~ s|</form>||g;
1.71      ng       4333: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4334: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4335: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4336: #		}
1.116     ng       4337: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.485     albertel 4338: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
1.71      ng       4339: 	    }
                   4340: 
1.257     albertel 4341: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4342: 
1.257     albertel 4343: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4344: 		if ($record{'version'} eq '') {
1.485     albertel 4345: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4346: 		} else {
1.116     ng       4347: 		    my %responseType = ();
                   4348: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4349: 			my @responseIds =$curRes->responseIds($partid);
                   4350: 			my @responseType =$curRes->responseType($partid);
                   4351: 			my %responseIds;
                   4352: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4353: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4354: 			}
                   4355: 			$responseType{$partid} = \%responseIds;
1.116     ng       4356: 		    }
1.148     albertel 4357: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4358: 
1.71      ng       4359: 		}
1.257     albertel 4360: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4361: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4362: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4363: 									$env{'request.course.id'},
1.71      ng       4364: 									'','.submission');
                   4365:  
                   4366: 	    }
1.103     albertel 4367: 	    if (&canmodify($usec)) {
                   4368: 		foreach my $partid (@{$parts}) {
                   4369: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4370: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4371: 		    $question++;
                   4372: 		}
1.196     albertel 4373: 		$prob++;
1.71      ng       4374: 	    }
                   4375: 	    $studentTable.='</td></tr>';
1.68      ng       4376: 
1.103     albertel 4377: 	}
1.68      ng       4378:         $curRes = $iterator->next();
                   4379:     }
                   4380: 
1.485     albertel 4381:     $studentTable.='</table>'."\n".
                   4382: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4383: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4384: 	'</form>'."\n";
1.324     albertel 4385:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4386:     $request->print($studentTable);
                   4387: 
                   4388:     return '';
1.119     ng       4389: }
                   4390: 
                   4391: sub displaySubByDates {
1.148     albertel 4392:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4393:     my $isCODE=0;
1.335     albertel 4394:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4395:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4396:     my $studentTable=&Apache::loncommon::start_data_table().
                   4397: 	&Apache::loncommon::start_data_table_header_row().
                   4398: 	'<th>'.&mt('Date/Time').'</th>'.
                   4399: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4400: 	'<th>'.&mt('Submission').'</th>'.
                   4401: 	'<th>'.&mt('Status').'</th>'.
                   4402: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4403:     my ($version);
                   4404:     my %mark;
1.148     albertel 4405:     my %orders;
1.119     ng       4406:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4407:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4408: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4409:     }
1.335     albertel 4410: 
                   4411:     my $interaction;
1.119     ng       4412:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4413: 	my $timestamp = 
                   4414: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4415: 	if (exists($$record{$version.':resource.0.version'})) {
                   4416: 	    $interaction = $$record{$version.':resource.0.version'};
                   4417: 	}
                   4418: 
                   4419: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4420: 		             : "$version:resource");
1.467     albertel 4421: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4422: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4423: 	if ($isCODE) {
                   4424: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4425: 	}
1.119     ng       4426: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4427: 	my @displaySub = ();
                   4428: 	foreach my $partid (@{$parts}) {
1.335     albertel 4429: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4430: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4431: 	    
                   4432: 
1.122     ng       4433: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4434: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4435: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4436: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4437: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4438: 
                   4439: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4440: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4441: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4442: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4443: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4444: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4445: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4446: 		    } else {
1.467     albertel 4447: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4448: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4449: 		    }
1.335     albertel 4450: 		    my $responseType=($isTask ? 'Task'
                   4451:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4452: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4453: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4454: 			$orders{$partid}->{$responseId}=
                   4455: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4456: 		    }
1.147     albertel 4457: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4458: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4459: 		}
                   4460: 	    }
1.335     albertel 4461: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4462: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4463: 				    $$record{"$where.$partid.checkedin"},
                   4464: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4465: 					'<br />';
1.335     albertel 4466: 	    }
                   4467: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4468: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4469: 		    lc($$record{"$where.$partid.award"}).' '.
                   4470: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4471: 		    '<br />';
                   4472: 	    }
1.335     albertel 4473: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4474: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4475: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4476: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4477: 		$displaySub[2].=
                   4478: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4479: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4480: 	    }
                   4481: 	}
                   4482: 	# needed because old essay regrader has not parts info
                   4483: 	if (exists $$record{"$version:resource.regrader"}) {
                   4484: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4485: 	}
                   4486: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4487: 	if ($displaySub[2]) {
1.467     albertel 4488: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4489: 	}
1.467     albertel 4490: 	$studentTable.='&nbsp;</td>'.
                   4491: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4492:     }
1.467     albertel 4493:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4494:     return $studentTable;
1.71      ng       4495: }
                   4496: 
                   4497: sub updateGradeByPage {
                   4498:     my ($request) = shift;
                   4499: 
1.257     albertel 4500:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4501:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4502:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4503:     my $pageTitle = $env{'form.page'};
1.103     albertel 4504:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4505:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4506:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4507:     if (!&canmodify($usec)) {
1.398     albertel 4508: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4509: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4510: 	return;
                   4511:     }
1.398     albertel 4512:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4513:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4514: 	'</h3>'."\n";
1.70      ng       4515: 
1.68      ng       4516:     $request->print($result);
                   4517: 
1.132     bowersj2 4518:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4519:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4520:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4521:     if (!$map) {
1.398     albertel 4522: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4523: 	my ($symb)=&get_symb($request);
                   4524: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4525: 	return; 
                   4526:     }
1.71      ng       4527:     my $iterator = $navmap->getIterator($map->map_start(),
                   4528: 					$map->map_finish());
1.70      ng       4529: 
1.484     albertel 4530:     my $studentTable=
                   4531: 	&Apache::loncommon::start_data_table().
                   4532: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4533: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4534: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4535: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4536: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4537: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4538: 
                   4539:     $iterator->next(); # skip the first BEGIN_MAP
                   4540:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4541:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4542:     while ($depth > 0) {
1.71      ng       4543:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4544:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4545: 
1.385     albertel 4546:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4547: 	    my $parts = $curRes->parts();
1.71      ng       4548:             my $title = $curRes->compTitle();
                   4549: 	    my $symbx = $curRes->symb();
1.484     albertel 4550: 	    $studentTable.=
                   4551: 		&Apache::loncommon::start_data_table_row().
                   4552: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4553: 		(scalar(@{$parts}) == 1 ? '' 
                   4554:                                         : '<br />('.&mt('[quant,_1,&nbsp;parts]',scalar(@{$parts}))
                   4555: 		 ).')</td>';
1.71      ng       4556: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4557: 
                   4558: 	    my %newrecord=();
                   4559: 	    my @displayPts=();
1.269     raeburn  4560:             my %aggregate = ();
                   4561:             my $aggregateflag = 0;
1.71      ng       4562: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4563: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4564: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4565: 
1.257     albertel 4566: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4567: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4568: 		my $partial = $newpts/$wgt;
                   4569: 		my $score;
                   4570: 		if ($partial > 0) {
                   4571: 		    $score = 'correct_by_override';
1.125     ng       4572: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4573: 		    $score = 'incorrect_by_override';
                   4574: 		}
1.257     albertel 4575: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4576: 		if ($dropMenu eq 'excused') {
1.71      ng       4577: 		    $partial = '';
                   4578: 		    $score = 'excused';
1.125     ng       4579: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4580: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4581: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4582: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4583: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4584: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4585: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4586: 		    $changeflag++;
                   4587: 		    $newpts = '';
1.269     raeburn  4588:                     
                   4589:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4590:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4591:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4592:                     if ($aggtries > 0) {
                   4593:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4594:                         $aggregateflag = 1;
                   4595:                     }
1.71      ng       4596: 		}
1.324     albertel 4597: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4598: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4599: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4600: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4601: 		    '&nbsp;<br />';
1.207     albertel 4602: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4603: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4604: 		    '&nbsp;<br />';
1.71      ng       4605: 		$question++;
1.380     albertel 4606: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4607: 
1.71      ng       4608: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4609: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4610: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4611: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4612: 
                   4613: 		$changeflag++;
                   4614: 	    }
                   4615: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4616: 		my %record = 
                   4617: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4618: 					     $udom,$uname);
                   4619: 
                   4620: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4621: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4622: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4623: 		    $newrecord{'resource.CODE'} = '';
                   4624: 		}
1.257     albertel 4625: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4626: 					$udom,$uname);
1.382     albertel 4627: 		%record = &Apache::lonnet::restore($symbx,
                   4628: 						   $env{'request.course.id'},
                   4629: 						   $udom,$uname);
1.380     albertel 4630: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4631: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4632: 	    }
1.380     albertel 4633: 	    
1.269     raeburn  4634:             if ($aggregateflag) {
                   4635:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4636:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4637:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4638:             }
1.125     ng       4639: 
1.71      ng       4640: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4641: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4642: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4643: 
1.196     albertel 4644: 	    $prob++;
1.68      ng       4645: 	}
1.71      ng       4646:         $curRes = $iterator->next();
1.68      ng       4647:     }
1.98      albertel 4648: 
1.484     albertel 4649:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4650:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4651:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4652: 		  'The scores were changed for '.
                   4653: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4654:     $request->print($grademsg.$studentTable);
1.68      ng       4655: 
1.70      ng       4656:     return '';
                   4657: }
                   4658: 
1.72      ng       4659: #-------- end of section for handling grading by page/sequence ---------
                   4660: #
                   4661: #-------------------------------------------------------------------
                   4662: 
1.75      albertel 4663: #--------------------Scantron Grading-----------------------------------
                   4664: #
                   4665: #------ start of section for handling grading by page/sequence ---------
                   4666: 
1.423     albertel 4667: =pod
                   4668: 
                   4669: =head1 Bubble sheet grading routines
                   4670: 
1.424     albertel 4671:   For this documentation:
                   4672: 
                   4673:    'scanline' refers to the full line of characters
                   4674:    from the file that we are parsing that represents one entire sheet
                   4675: 
                   4676:    'bubble line' refers to the data
                   4677:    representing the line of bubbles that are on the physical bubble sheet
                   4678: 
                   4679: 
                   4680: The overall process is that a scanned in bubble sheet data is uploaded
                   4681: into a course. When a user wants to grade, they select a
                   4682: sequence/folder of resources, a file of bubble sheet info, and pick
                   4683: one of the predefined configurations for what each scanline looks
                   4684: like.
                   4685: 
                   4686: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4687: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4688: because too light bubbling), 'double bubble' (each bubble line should
                   4689: have no more that one letter picked), invalid or duplicated CODE,
                   4690: invalid student ID
                   4691: 
                   4692: If the CODE option is used that determines the randomization of the
                   4693: homework problems, either way the student ID is looked up into a
                   4694: username:domain.
                   4695: 
                   4696: During the validation phase the instructor can choose to skip scanlines. 
                   4697: 
1.435     foxr     4698: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4699: 
                   4700:   scantron_original_filename (unmodified original file)
                   4701:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4702:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4703: 
                   4704: Also there is a separate hash nohist_scantrondata that contains extra
                   4705: correction information that isn't representable in the bubble sheet
                   4706: file (see &scantron_getfile() for more information)
                   4707: 
                   4708: After all scanlines are either valid, marked as valid or skipped, then
                   4709: foreach line foreach problem in the picked sequence, an ssi request is
                   4710: made that simulates a user submitting their selected letter(s) against
                   4711: the homework problem.
1.423     albertel 4712: 
                   4713: =over 4
                   4714: 
                   4715: 
                   4716: 
                   4717: =item defaultFormData
                   4718: 
                   4719:   Returns html hidden inputs used to hold context/default values.
                   4720: 
                   4721:  Arguments:
                   4722:   $symb - $symb of the current resource 
                   4723: 
                   4724: =cut
1.422     foxr     4725: 
1.81      albertel 4726: sub defaultFormData {
1.324     albertel 4727:     my ($symb)=@_;
1.447     foxr     4728:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4729:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4730:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4731: }
                   4732: 
1.447     foxr     4733: 
1.423     albertel 4734: =pod 
                   4735: 
                   4736: =item getSequenceDropDown
                   4737: 
                   4738:    Return html dropdown of possible sequences to grade
                   4739:  
                   4740:  Arguments:
                   4741:    $symb - $symb of the current resource 
                   4742: 
                   4743: =cut
1.422     foxr     4744: 
1.75      albertel 4745: sub getSequenceDropDown {
1.423     albertel 4746:     my ($symb)=@_;
1.75      albertel 4747:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4748:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4749:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4750:     my $ctr=0;
                   4751:     foreach (@$titles) {
                   4752: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4753: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4754: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4755: 	    '>'.$showtitle.'</option>'."\n";
                   4756: 	$ctr++;
                   4757:     }
                   4758:     $result.= '</select>';
                   4759:     return $result;
                   4760: }
                   4761: 
1.495     albertel 4762: my %bubble_lines_per_response;     # no. bubble lines for each response.
                   4763:                                    # index is "symb.part_id"
                   4764: 
                   4765: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4766: 
1.509     raeburn  4767: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4768:                                    # matchresponse or rankresponse, where 
                   4769:                                    # an individual response can have multiple 
                   4770:                                    # lines
1.503     raeburn  4771: 
                   4772: my %responsetype_per_response;     # responsetype for each response
                   4773: 
1.495     albertel 4774: # Save and restore the bubble lines array to the form env.
                   4775: 
                   4776: 
                   4777: sub save_bubble_lines {
                   4778:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4779: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4780: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4781: 	    $first_bubble_line{$line};
1.503     raeburn  4782:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4783:             $subdivided_bubble_lines{$line};
                   4784:         $env{"form.scantron.responsetype.$line"} =
                   4785:             $responsetype_per_response{$line};
1.495     albertel 4786:     }
                   4787: }
                   4788: 
                   4789: 
                   4790: sub restore_bubble_lines {
                   4791:     my $line = 0;
                   4792:     %bubble_lines_per_response = ();
                   4793:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4794: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4795: 	$bubble_lines_per_response{$line} = $value;
                   4796: 	$first_bubble_line{$line}  =
                   4797: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4798:         $subdivided_bubble_lines{$line} =
                   4799:             $env{"form.scantron.sub_bubblelines.$line"};
                   4800:         $responsetype_per_response{$line} =
                   4801:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4802: 	$line++;
                   4803:     }
                   4804: 
                   4805: }
                   4806: 
                   4807: #  Given the parsed scanline, get the response for 
                   4808: #  'answer' number n:
                   4809: 
                   4810: sub get_response_bubbles {
                   4811:     my ($parsed_line, $response)  = @_;
                   4812: 
                   4813: 
                   4814:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4815:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4816:     
                   4817:     my $selected = "";
                   4818: 
                   4819:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4820: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4821: 	$bubble_line++;
                   4822:     }
                   4823:     return $selected;
                   4824: }
1.423     albertel 4825: 
                   4826: =pod 
                   4827: 
                   4828: =item scantron_filenames
                   4829: 
                   4830:    Returns a list of the scantron files in the current course 
                   4831: 
                   4832: =cut
1.422     foxr     4833: 
1.202     albertel 4834: sub scantron_filenames {
1.257     albertel 4835:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4836:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4837:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4838: 				    &propath($cdom,$cname));
1.202     albertel 4839:     my @possiblenames;
1.201     albertel 4840:     foreach my $filename (sort(@files)) {
1.157     albertel 4841: 	($filename)=split(/&/,$filename);
                   4842: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4843: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4844: 	push(@possiblenames,$filename);
                   4845:     }
                   4846:     return @possiblenames;
                   4847: }
                   4848: 
1.423     albertel 4849: =pod 
                   4850: 
                   4851: =item scantron_uploads
                   4852: 
                   4853:    Returns  html drop-down list of scantron files in current course.
                   4854: 
                   4855:  Arguments:
                   4856:    $file2grade - filename to set as selected in the dropdown
                   4857: 
                   4858: =cut
1.422     foxr     4859: 
1.202     albertel 4860: sub scantron_uploads {
1.209     ng       4861:     my ($file2grade) = @_;
1.202     albertel 4862:     my $result=	'<select name="scantron_selectfile">';
                   4863:     $result.="<option></option>";
                   4864:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4865: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4866:     }
                   4867:     $result.="</select>";
                   4868:     return $result;
                   4869: }
                   4870: 
1.423     albertel 4871: =pod 
                   4872: 
                   4873: =item scantron_scantab
                   4874: 
                   4875:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4876:   file.
                   4877: 
                   4878: =cut
1.422     foxr     4879: 
1.82      albertel 4880: sub scantron_scantab {
                   4881:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4882:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4883:     $result.='<option></option>'."\n";
1.82      albertel 4884:     foreach my $line (<$fh>) {
                   4885: 	my ($name,$descrip)=split(/:/,$line);
                   4886: 	if ($name =~ /^\#/) { next; }
                   4887: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4888:     }
                   4889:     $result.='</select>'."\n";
                   4890: 
                   4891:     return $result;
                   4892: }
                   4893: 
1.423     albertel 4894: =pod 
                   4895: 
                   4896: =item scantron_CODElist
                   4897: 
                   4898:   Returns html drop down of the saved CODE lists from current course,
                   4899:   generated from earlier printings.
                   4900: 
                   4901: =cut
1.422     foxr     4902: 
1.186     albertel 4903: sub scantron_CODElist {
1.257     albertel 4904:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4905:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4906:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4907:     my $namechoice='<option></option>';
1.225     albertel 4908:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4909: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4910: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4911: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4912:     }
                   4913:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4914:     return $namechoice;
                   4915: }
                   4916: 
1.423     albertel 4917: =pod 
                   4918: 
                   4919: =item scantron_CODEunique
                   4920: 
                   4921:   Returns the html for "Each CODE to be used once" radio.
                   4922: 
                   4923: =cut
1.422     foxr     4924: 
1.186     albertel 4925: sub scantron_CODEunique {
1.381     albertel 4926:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4927:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4928:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4929:                 </span>
                   4930:                 <span style="white-space: nowrap;">
1.272     albertel 4931:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4932:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4933:                 </span>';
1.186     albertel 4934:     return $result;
                   4935: }
1.423     albertel 4936: 
                   4937: =pod 
                   4938: 
                   4939: =item scantron_selectphase
                   4940: 
                   4941:   Generates the initial screen to start the bubble sheet process.
                   4942:   Allows for - starting a grading run.
1.424     albertel 4943:              - downloading existing scan data (original, corrected
1.423     albertel 4944:                                                 or skipped info)
                   4945: 
                   4946:              - uploading new scan data
                   4947: 
                   4948:  Arguments:
                   4949:   $r          - The Apache request object
                   4950:   $file2grade - name of the file that contain the scanned data to score
                   4951: 
                   4952: =cut
1.186     albertel 4953: 
1.75      albertel 4954: sub scantron_selectphase {
1.209     ng       4955:     my ($r,$file2grade) = @_;
1.324     albertel 4956:     my ($symb)=&get_symb($r);
1.75      albertel 4957:     if (!$symb) {return '';}
1.423     albertel 4958:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4959:     my $default_form_data=&defaultFormData($symb);
                   4960:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4961:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4962:     my $format_selector=&scantron_scantab();
1.186     albertel 4963:     my $CODE_selector=&scantron_CODElist();
                   4964:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4965:     my $result;
1.422     foxr     4966: 
1.513     foxr     4967:     $ssi_error = 0;
                   4968: 
1.422     foxr     4969:     # Chunk of form to prompt for a file to grade and how:
                   4970: 
1.489     albertel 4971:     $result.= '
                   4972:     <br />
                   4973:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   4974:     <input type="hidden" name="command" value="scantron_warning" />
                   4975:     '.$default_form_data.'
                   4976:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   4977:        '.&Apache::loncommon::start_data_table_header_row().'
                   4978:             <th colspan="2">
1.492     albertel 4979:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 4980:             </th>
                   4981:        '.&Apache::loncommon::end_data_table_header_row().'
                   4982:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4983:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 4984:        '.&Apache::loncommon::end_data_table_row().'
                   4985:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4986:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 4987:        '.&Apache::loncommon::end_data_table_row().'
                   4988:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4989:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 4990:        '.&Apache::loncommon::end_data_table_row().'
                   4991:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4992:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 4993:        '.&Apache::loncommon::end_data_table_row().'
                   4994:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4995:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 4996:        '.&Apache::loncommon::end_data_table_row().'
                   4997:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4998: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 4999:             <td>
1.492     albertel 5000: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5001:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5002:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5003: 	    </td>
1.489     albertel 5004:        '.&Apache::loncommon::end_data_table_row().'
                   5005:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5006:             <td colspan="2">
1.492     albertel 5007:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
1.162     albertel 5008:             </td>
1.489     albertel 5009:        '.&Apache::loncommon::end_data_table_row().'
                   5010:     '.&Apache::loncommon::end_data_table().'
                   5011:     </form>
                   5012: ';
1.162     albertel 5013:    
                   5014:     $r->print($result);
                   5015: 
1.257     albertel 5016:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5017:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5018: 
1.422     foxr     5019: 	# Chunk of form to prompt for a scantron file upload.
                   5020: 
1.489     albertel 5021:         $r->print('
                   5022:     <br />
                   5023:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5024:        '.&Apache::loncommon::start_data_table_header_row().'
                   5025:             <th>
1.492     albertel 5026:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
1.489     albertel 5027:             </th>
                   5028:        '.&Apache::loncommon::end_data_table_header_row().'
                   5029:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5030:             <td>
1.489     albertel 5031: ');
1.324     albertel 5032:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5033:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5034:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5035:     $r->print('
1.174     albertel 5036:               <script type="text/javascript" language="javascript">
                   5037:     function checkUpload(formname) {
                   5038: 	if (formname.upfile.value == "") {
1.492     albertel 5039: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5040: 	    return false;
                   5041: 	}
                   5042: 	formname.submit();
                   5043:     }
                   5044:               </script>
                   5045: 
1.492     albertel 5046:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5047:                 '.$default_form_data.'
                   5048:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5049:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5050:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5051:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5052:                 <br />
1.492     albertel 5053:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.174     albertel 5054:               </form>
1.492     albertel 5055: ');
1.162     albertel 5056: 
1.489     albertel 5057:         $r->print('
1.162     albertel 5058:             </td>
1.489     albertel 5059:        '.&Apache::loncommon::end_data_table_row().'
                   5060:        '.&Apache::loncommon::end_data_table().'
                   5061: ');
1.162     albertel 5062:     }
1.422     foxr     5063: 
                   5064:     # Chunk of the form that prompts to view a scoring office file,
                   5065:     # corrected file, skipped records in a file.
                   5066: 
1.489     albertel 5067:     $r->print('
                   5068:    <br />
                   5069:    <form action="/adm/grades" name="scantron_download">
                   5070:      '.$default_form_data.'
                   5071:      <input type="hidden" name="command" value="scantron_download" />
                   5072:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5073:        '.&Apache::loncommon::start_data_table_header_row().'
                   5074:               <th>
1.492     albertel 5075:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5076:               </th>
                   5077:        '.&Apache::loncommon::end_data_table_header_row().'
                   5078:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5079:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5080:                 <br />
1.492     albertel 5081:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5082:        '.&Apache::loncommon::end_data_table_row().'
                   5083:      '.&Apache::loncommon::end_data_table().'
                   5084:    </form>
                   5085:    <br />
                   5086: ');
1.162     albertel 5087: 
1.457     banghart 5088:     &Apache::lonpickcode::code_list($r,2);
                   5089:     $r->print($grading_menu_button);
1.162     albertel 5090:     return
1.75      albertel 5091: }
                   5092: 
1.423     albertel 5093: =pod
                   5094: 
                   5095: =item get_scantron_config
                   5096: 
                   5097:    Parse and return the scantron configuration line selected as a
                   5098:    hash of configuration file fields.
                   5099: 
                   5100:  Arguments:
                   5101:     which - the name of the configuration to parse from the file.
                   5102: 
                   5103: 
                   5104:  Returns:
                   5105:             If the named configuration is not in the file, an empty
                   5106:             hash is returned.
                   5107:     a hash with the fields
                   5108:       name         - internal name for the this configuration setup
                   5109:       description  - text to display to operator that describes this config
                   5110:       CODElocation - if 0 or the string 'none'
                   5111:                           - no CODE exists for this config
                   5112:                      if -1 || the string 'letter'
                   5113:                           - a CODE exists for this config and is
                   5114:                             a string of letters
                   5115:                      Unsupported value (but planned for future support)
                   5116:                           if a positive integer
                   5117:                                - The CODE exists as the first n items from
                   5118:                                  the question section of the form
                   5119:                           if the string 'number'
                   5120:                                - The CODE exists for this config and is
                   5121:                                  a string of numbers
                   5122:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5123:                      the CODE starts
                   5124:       CODElength  - length of the CODE
                   5125:       IDstart     - column where the student ID number starts
                   5126:       IDlength    - length of the student ID info
                   5127:       Qstart      - column where the information from the bubbled
                   5128:                     'questions' start
                   5129:       Qlength     - number of columns comprising a single bubble line from
                   5130:                     the sheet. (usually either 1 or 10)
1.424     albertel 5131:       Qon         - either a single character representing the character used
1.423     albertel 5132:                     to signal a bubble was chosen in the positional setup, or
                   5133:                     the string 'letter' if the letter of the chosen bubble is
                   5134:                     in the final, or 'number' if a number representing the
                   5135:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5136:       Qoff        - the character used to represent that a bubble was
                   5137:                     left blank
1.423     albertel 5138:       PaperID     - if the scanning process generates a unique number for each
                   5139:                     sheet scanned the column that this ID number starts in
                   5140:       PaperIDlength - number of columns that comprise the unique ID number
                   5141:                       for the sheet of paper
1.424     albertel 5142:       FirstName   - column that the first name starts in
1.423     albertel 5143:       FirstNameLength - number of columns that the first name spans
                   5144:  
                   5145:       LastName    - column that the last name starts in
                   5146:       LastNameLength - number of columns that the last name spans
                   5147: 
                   5148: =cut
1.422     foxr     5149: 
1.82      albertel 5150: sub get_scantron_config {
                   5151:     my ($which) = @_;
                   5152:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5153:     my %config;
1.157     albertel 5154:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 5155:     foreach my $line (<$fh>) {
                   5156: 	my ($name,$descrip)=split(/:/,$line);
                   5157: 	if ($name ne $which ) { next; }
                   5158: 	chomp($line);
                   5159: 	my @config=split(/:/,$line);
                   5160: 	$config{'name'}=$config[0];
                   5161: 	$config{'description'}=$config[1];
                   5162: 	$config{'CODElocation'}=$config[2];
                   5163: 	$config{'CODEstart'}=$config[3];
                   5164: 	$config{'CODElength'}=$config[4];
                   5165: 	$config{'IDstart'}=$config[5];
                   5166: 	$config{'IDlength'}=$config[6];
                   5167: 	$config{'Qstart'}=$config[7];
1.497     foxr     5168:  	$config{'Qlength'}=$config[8];
1.82      albertel 5169: 	$config{'Qoff'}=$config[9];
                   5170: 	$config{'Qon'}=$config[10];
1.157     albertel 5171: 	$config{'PaperID'}=$config[11];
                   5172: 	$config{'PaperIDlength'}=$config[12];
                   5173: 	$config{'FirstName'}=$config[13];
                   5174: 	$config{'FirstNamelength'}=$config[14];
                   5175: 	$config{'LastName'}=$config[15];
                   5176: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5177: 	last;
                   5178:     }
                   5179:     return %config;
                   5180: }
                   5181: 
1.423     albertel 5182: =pod 
                   5183: 
                   5184: =item username_to_idmap
                   5185: 
                   5186:     creates a hash keyed by student id with values of the corresponding
                   5187:     student username:domain.
                   5188: 
                   5189:   Arguments:
                   5190: 
                   5191:     $classlist - reference to the class list hash. This is a hash
                   5192:                  keyed by student name:domain  whose elements are references
1.424     albertel 5193:                  to arrays containing various chunks of information
1.423     albertel 5194:                  about the student. (See loncoursedata for more info).
                   5195: 
                   5196:   Returns
                   5197:     %idmap - the constructed hash
                   5198: 
                   5199: =cut
                   5200: 
1.82      albertel 5201: sub username_to_idmap {
                   5202:     my ($classlist)= @_;
                   5203:     my %idmap;
                   5204:     foreach my $student (keys(%$classlist)) {
                   5205: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5206: 	    $student;
                   5207:     }
                   5208:     return %idmap;
                   5209: }
1.423     albertel 5210: 
                   5211: =pod
                   5212: 
1.424     albertel 5213: =item scantron_fixup_scanline
1.423     albertel 5214: 
                   5215:    Process a requested correction to a scanline.
                   5216: 
                   5217:   Arguments:
                   5218:     $scantron_config   - hash from &get_scantron_config()
                   5219:     $scan_data         - hash of correction information 
                   5220:                           (see &scantron_getfile())
                   5221:     $line              - existing scanline
                   5222:     $whichline         - line number of the passed in scanline
                   5223:     $field             - type of change to process 
                   5224:                          (either 
                   5225:                           'ID'     -> correct the student ID number
                   5226:                           'CODE'   -> correct the CODE
                   5227:                           'answer' -> fixup the submitted answers)
                   5228:     
                   5229:    $args               - hash of additional info,
                   5230:                           - 'ID' 
                   5231:                                'newid' -> studentID to use in replacement
1.424     albertel 5232:                                           of existing one
1.423     albertel 5233:                           - 'CODE' 
                   5234:                                'CODE_ignore_dup' - set to true if duplicates
                   5235:                                                    should be ignored.
                   5236: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5237:                                         if the existing unfound code should
1.423     albertel 5238:                                         be used as is
                   5239:                           - 'answer'
                   5240:                                'response' - new answer or 'none' if blank
                   5241:                                'question' - the bubble line to change
1.503     raeburn  5242:                                'questionnum' - the question identifier,
                   5243:                                                may include subquestion. 
1.423     albertel 5244: 
                   5245:   Returns:
                   5246:     $line - the modified scanline
                   5247: 
                   5248:   Side effects: 
                   5249:     $scan_data - may be updated
                   5250: 
                   5251: =cut
                   5252: 
1.82      albertel 5253: 
1.157     albertel 5254: sub scantron_fixup_scanline {
                   5255:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5256:     if ($field eq 'ID') {
                   5257: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5258: 	    return ($line,1,'New value too large');
1.157     albertel 5259: 	}
                   5260: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5261: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5262: 				     $args->{'newid'});
                   5263: 	}
                   5264: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5265: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5266: 	if ($args->{'newid'}=~/^\s*$/) {
                   5267: 	    &scan_data($scan_data,"$whichline.user",
                   5268: 		       $args->{'username'}.':'.$args->{'domain'});
                   5269: 	}
1.186     albertel 5270:     } elsif ($field eq 'CODE') {
1.192     albertel 5271: 	if ($args->{'CODE_ignore_dup'}) {
                   5272: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5273: 	}
                   5274: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5275: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5276: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5277: 		return ($line,1,'New CODE value too large');
                   5278: 	    }
                   5279: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5280: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5281: 	    }
                   5282: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5283: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5284: 	}
1.157     albertel 5285:     } elsif ($field eq 'answer') {
1.497     foxr     5286: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5287: 	my $off=$scantron_config->{'Qoff'};
                   5288: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5289: 	my $answer=${off}x$length;
                   5290: 	if ($args->{'response'} eq 'none') {
                   5291: 	    &scan_data($scan_data,
1.503     raeburn  5292: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5293: 	} else {
                   5294: 	    if ($on eq 'letter') {
                   5295: 		my @alphabet=('A'..'Z');
                   5296: 		$answer=$alphabet[$args->{'response'}];
                   5297: 	    } elsif ($on eq 'number') {
                   5298: 		$answer=$args->{'response'}+1;
                   5299: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5300: 	    } else {
1.497     foxr     5301: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5302: 	    }
1.497     foxr     5303: 	    &scan_data($scan_data,
1.503     raeburn  5304: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5305: 	}
1.497     foxr     5306: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5307: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5308:     }
                   5309:     return $line;
                   5310: }
1.423     albertel 5311: 
                   5312: =pod
                   5313: 
                   5314: =item scan_data
                   5315: 
                   5316:     Edit or look up  an item in the scan_data hash.
                   5317: 
                   5318:   Arguments:
                   5319:     $scan_data  - The hash (see scantron_getfile)
                   5320:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5321:                   scantronfilename_key).
1.423     albertel 5322:     $data        - New value of the hash entry.
                   5323:     $delete      - If true, the entry is removed from the hash.
                   5324: 
                   5325:   Returns:
                   5326:     The new value of the hash table field (undefined if deleted).
                   5327: 
                   5328: =cut
                   5329: 
                   5330: 
1.157     albertel 5331: sub scan_data {
                   5332:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5333:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5334:     if (defined($value)) {
                   5335: 	$scan_data->{$filename.'_'.$key} = $value;
                   5336:     }
                   5337:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5338:     return $scan_data->{$filename.'_'.$key};
                   5339: }
1.423     albertel 5340: 
1.495     albertel 5341: # ----- These first few routines are general use routines.----
                   5342: 
                   5343: # Return the number of occurences of a pattern in a string.
                   5344: 
                   5345: sub occurence_count {
                   5346:     my ($string, $pattern) = @_;
                   5347: 
                   5348:     my @matches = ($string =~ /$pattern/g);
                   5349: 
                   5350:     return scalar(@matches);
                   5351: }
                   5352: 
                   5353: 
                   5354: # Take a string known to have digits and convert all the
                   5355: # digits into letters in the range J,A..I.
                   5356: 
                   5357: sub digits_to_letters {
                   5358:     my ($input) = @_;
                   5359: 
                   5360:     my @alphabet = ('J', 'A'..'I');
                   5361: 
                   5362:     my @input    = split(//, $input);
                   5363:     my $output ='';
                   5364:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5365: 	if ($input[$i] =~ /\d/) {
                   5366: 	    $output .= $alphabet[$input[$i]];
                   5367: 	} else {
                   5368: 	    $output .= $input[$i];
                   5369: 	}
                   5370:     }
                   5371:     return $output;
                   5372: }
                   5373: 
1.423     albertel 5374: =pod 
                   5375: 
                   5376: =item scantron_parse_scanline
                   5377: 
                   5378:   Decodes a scanline from the selected scantron file
                   5379: 
                   5380:  Arguments:
                   5381:     line             - The text of the scantron file line to process
                   5382:     whichline        - Line number
                   5383:     scantron_config  - Hash describing the format of the scantron lines.
                   5384:     scan_data        - Hash of extra information about the scanline
                   5385:                        (see scantron_getfile for more information)
                   5386:     just_header      - True if should not process question answers but only
                   5387:                        the stuff to the left of the answers.
                   5388:  Returns:
                   5389:    Hash containing the result of parsing the scanline
                   5390: 
                   5391:    Keys are all proceeded by the string 'scantron.'
                   5392: 
                   5393:        CODE    - the CODE in use for this scanline
                   5394:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5395:                  by the operator
                   5396:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5397:                             CODEs were selected, but the usage has been
                   5398:                             forced by the operator
                   5399:        ID  - student ID
                   5400:        PaperID - if used, the ID number printed on the sheet when the 
                   5401:                  paper was scanned
                   5402:        FirstName - first name from the sheet
                   5403:        LastName  - last name from the sheet
                   5404: 
                   5405:      if just_header was not true these key may also exist
                   5406: 
1.447     foxr     5407:        missingerror - a list of bubble ranges that are considered to be answers
                   5408:                       to a single question that don't have any bubbles filled in.
                   5409:                       Of the form questionnumber:firstbubblenumber:count.
                   5410:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5411:                       to a single question that have more than one bubble filled in.
                   5412:                       Of the form questionnumber::firstbubblenumber:count
                   5413:    
                   5414:                 In the above, count is the number of bubble responses in the
                   5415:                 input line needed to represent the possible answers to the question.
                   5416:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5417:                 per line would have count = 2.
                   5418: 
1.423     albertel 5419:        maxquest     - the number of the last bubble line that was parsed
                   5420: 
                   5421:        (<number> starts at 1)
                   5422:        <number>.answer - zero or more letters representing the selected
                   5423:                          letters from the scanline for the bubble line 
                   5424:                          <number>.
                   5425:                          if blank there was either no bubble or there where
                   5426:                          multiple bubbles, (consult the keys missingerror and
                   5427:                          doubleerror if this is an error condition)
                   5428: 
                   5429: =cut
                   5430: 
1.82      albertel 5431: sub scantron_parse_scanline {
1.423     albertel 5432:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5433: 
1.82      albertel 5434:     my %record;
1.422     foxr     5435:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5436:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5437:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5438: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5439: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5440: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5441: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5442: 	    $record{'scantron.CODE'}=substr($data,
                   5443: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5444: 					    $$scantron_config{'CODElength'});
1.191     albertel 5445: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5446: 		$record{'scantron.useCODE'}=1;
                   5447: 	    }
1.192     albertel 5448: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5449: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5450: 	    }
1.82      albertel 5451: 	} else {
                   5452: 	    #FIXME interpret first N questions
                   5453: 	}
                   5454:     }
1.83      albertel 5455:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5456: 				  $$scantron_config{'IDlength'});
1.157     albertel 5457:     $record{'scantron.PaperID'}=
                   5458: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5459: 	       $$scantron_config{'PaperIDlength'});
                   5460:     $record{'scantron.FirstName'}=
                   5461: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5462: 	       $$scantron_config{'FirstNamelength'});
                   5463:     $record{'scantron.LastName'}=
                   5464: 	substr($data,$$scantron_config{'LastName'}-1,
                   5465: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5466:     if ($just_header) { return \%record; }
1.194     albertel 5467: 
1.82      albertel 5468:     my @alphabet=('A'..'Z');
                   5469:     my $questnum=0;
1.447     foxr     5470:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5471: 
1.470     foxr     5472:     chomp($questions);		# Get rid of any trailing \n.
                   5473:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5474:     while (length($questions)) {
1.447     foxr     5475: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5476:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5477:                              || 1;
                   5478:         $questnum++;
                   5479:         my $quest_id = $questnum;
                   5480:         my $currentquest = substr($questions,0,$answer_length);
                   5481:         $questions       = substr($questions,$answer_length);
                   5482:         if (length($currentquest) < $answer_length) { next; }
                   5483: 
                   5484:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5485:             my $subquestnum = 1;
                   5486:             my $subquestions = $currentquest;
                   5487:             my @subanswers_needed = 
                   5488:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5489:             foreach my $subans (@subanswers_needed) {
                   5490:                 my $subans_length =
                   5491:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5492:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5493:                 $subquestions   = substr($subquestions,$subans_length);
                   5494:                 $quest_id = "$questnum.$subquestnum";
                   5495:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5496:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5497:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5498:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5499:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5500:                 } else {
                   5501:                     $ansnum = &scantron_validator_positional($ansnum,
                   5502:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5503:                 }
                   5504:                 $subquestnum ++;
                   5505:             }
                   5506:         } else {
                   5507:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5508:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5509:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5510:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5511:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5512:             } else {
                   5513:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5514:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5515:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5516:             }
                   5517:         }
                   5518:     }
                   5519:     $record{'scantron.maxquest'}=$questnum;
                   5520:     return \%record;
                   5521: }
1.447     foxr     5522: 
1.503     raeburn  5523: sub scantron_validator_lettnum {
                   5524:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5525:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5526: 
                   5527:     # Qon 'letter' implies for each slot in currquest we have:
                   5528:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5529:     #    about anything else (esp. a value of Qoff) for missing
                   5530:     #    bubbles.
                   5531:     #
                   5532:     # Qon 'number' implies each slot gives a digit that indexes the
                   5533:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5534:     #    and * or ? for double bubbles on a single line.
                   5535:     #
1.447     foxr     5536: 
1.503     raeburn  5537:     my $matchon;
                   5538:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5539:         $matchon = '[A-Z]';
                   5540:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5541:         $matchon = '\d';
                   5542:     }
                   5543:     my $occurrences = 0;
                   5544:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5545:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5546:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5547:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5548:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5549:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5550:         my @singlelines = split('',$currquest);
                   5551:         foreach my $entry (@singlelines) {
                   5552:             $occurrences = &occurence_count($entry,$matchon);
                   5553:             if ($occurrences > 1) {
                   5554:                 last;
                   5555:             }
                   5556:         } 
                   5557:     } else {
                   5558:         $occurrences = &occurence_count($currquest,$matchon); 
                   5559:     }
                   5560:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5561:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5562:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5563:             my $bubble = substr($currquest,$ans,1);
                   5564:             if ($bubble =~ /$matchon/ ) {
                   5565:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5566:                     if ($bubble == 0) {
                   5567:                         $bubble = 10; 
                   5568:                     }
                   5569:                     $record->{"scantron.$ansnum.answer"} = 
                   5570:                         $alphabet->[$bubble-1];
                   5571:                 } else {
                   5572:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5573:                 }
                   5574:             } else {
                   5575:                 $record->{"scantron.$ansnum.answer"}='';
                   5576:             }
                   5577:             $ansnum++;
                   5578:         }
                   5579:     } elsif (!defined($currquest)
                   5580:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5581:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5582:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5583:             $record->{"scantron.$ansnum.answer"}='';
                   5584:             $ansnum++;
                   5585:         }
                   5586:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5587:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5588:         }
                   5589:     } else {
                   5590:         if ($$scantron_config{'Qon'} eq 'number') {
                   5591:             $currquest = &digits_to_letters($currquest);            
                   5592:         }
                   5593:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5594:             my $bubble = substr($currquest,$ans,1);
                   5595:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5596:             $ansnum++;
                   5597:         }
                   5598:     }
                   5599:     return $ansnum;
                   5600: }
1.447     foxr     5601: 
1.503     raeburn  5602: sub scantron_validator_positional {
                   5603:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5604:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5605: 
1.503     raeburn  5606:     # Otherwise there's a positional notation;
                   5607:     # each bubble line requires Qlength items, and there are filled in
                   5608:     # bubbles for each case where there 'Qon' characters.
                   5609:     #
1.447     foxr     5610: 
1.503     raeburn  5611:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5612: 
1.503     raeburn  5613:     # If the split only gives us one element.. the full length of the
                   5614:     # answer string, no bubbles are filled in:
1.447     foxr     5615: 
1.507     raeburn  5616:     if ($answers_needed eq '') {
                   5617:         return;
                   5618:     }
                   5619: 
1.503     raeburn  5620:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5621:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5622:             $record->{"scantron.$ansnum.answer"}='';
                   5623:             $ansnum++;
                   5624:         }
                   5625:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5626:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5627:         }
                   5628:     } elsif (scalar(@array) == 2) {
                   5629:         my $location = length($array[0]);
                   5630:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5631:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5632:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5633:             if ($ans eq $line_num) {
                   5634:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5635:             } else {
                   5636:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5637:             }
                   5638:             $ansnum++;
                   5639:          }
                   5640:     } else {
                   5641:         #  If there's more than one instance of a bubble character
                   5642:         #  That's a double bubble; with positional notation we can
                   5643:         #  record all the bubbles filled in as well as the
                   5644:         #  fact this response consists of multiple bubbles.
                   5645:         #
                   5646:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5647:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5648:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5649:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5650:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5651:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5652:             my $doubleerror = 0;
                   5653:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5654:                    (!$doubleerror)) {
                   5655:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5656:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5657:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5658:                if (length(@currarray) > 2) {
                   5659:                    $doubleerror = 1;
                   5660:                } 
                   5661:             }
                   5662:             if ($doubleerror) {
                   5663:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5664:             }
                   5665:         } else {
                   5666:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5667:         }
                   5668:         my $item = $ansnum;
                   5669:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5670:             $record->{"scantron.$item.answer"} = '';
                   5671:             $item ++;
                   5672:         }
1.447     foxr     5673: 
1.503     raeburn  5674:         my @ans=@array;
                   5675:         my $i=0;
                   5676:         my $increment = 0;
                   5677:         while ($#ans) {
                   5678:             $i+=length($ans[0]) + $increment;
                   5679:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5680:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5681:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5682:             shift(@ans);
                   5683:             $increment = 1;
                   5684:         }
                   5685:         $ansnum += $answers_needed;
1.82      albertel 5686:     }
1.503     raeburn  5687:     return $ansnum;
1.82      albertel 5688: }
                   5689: 
1.423     albertel 5690: =pod
                   5691: 
                   5692: =item scantron_add_delay
                   5693: 
                   5694:    Adds an error message that occurred during the grading phase to a
                   5695:    queue of messages to be shown after grading pass is complete
                   5696: 
                   5697:  Arguments:
1.424     albertel 5698:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5699:    $scanline    - the scanline that caused the error
                   5700:    $errormesage - the error message
                   5701:    $errorcode   - a numeric code for the error
                   5702: 
                   5703:  Side Effects:
1.424     albertel 5704:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5705: 
                   5706: =cut
                   5707: 
1.82      albertel 5708: sub scantron_add_delay {
1.140     albertel 5709:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5710:     push(@$delayqueue,
                   5711: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5712: 	  'ecode' => $errorcode }
                   5713: 	 );
1.82      albertel 5714: }
                   5715: 
1.423     albertel 5716: =pod
                   5717: 
                   5718: =item scantron_find_student
                   5719: 
1.424     albertel 5720:    Finds the username for the current scanline
                   5721: 
                   5722:   Arguments:
                   5723:    $scantron_record - hash result from scantron_parse_scanline
                   5724:    $scan_data       - hash of correction information 
                   5725:                       (see &scantron_getfile() form more information)
                   5726:    $idmap           - hash from &username_to_idmap()
                   5727:    $line            - number of current scanline
                   5728:  
                   5729:   Returns:
                   5730:    Either 'username:domain' or undef if unknown
                   5731: 
1.423     albertel 5732: =cut
                   5733: 
1.82      albertel 5734: sub scantron_find_student {
1.157     albertel 5735:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5736:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5737:     if ($scanID =~ /^\s*$/) {
                   5738:  	return &scan_data($scan_data,"$line.user");
                   5739:     }
1.83      albertel 5740:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5741:  	if (lc($id) eq lc($scanID)) {
                   5742:  	    return $$idmap{$id};
                   5743:  	}
1.83      albertel 5744:     }
                   5745:     return undef;
                   5746: }
                   5747: 
1.423     albertel 5748: =pod
                   5749: 
                   5750: =item scantron_filter
                   5751: 
1.424     albertel 5752:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5753:    hidden resources was selected
                   5754: 
1.423     albertel 5755: =cut
                   5756: 
1.83      albertel 5757: sub scantron_filter {
                   5758:     my ($curres)=@_;
1.331     albertel 5759: 
                   5760:     if (ref($curres) && $curres->is_problem()) {
                   5761: 	# if the user has asked to not have either hidden
                   5762: 	# or 'randomout' controlled resources to be graded
                   5763: 	# don't include them
                   5764: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5765: 	    && $curres->randomout) {
                   5766: 	    return 0;
                   5767: 	}
1.83      albertel 5768: 	return 1;
                   5769:     }
                   5770:     return 0;
1.82      albertel 5771: }
                   5772: 
1.423     albertel 5773: =pod
                   5774: 
                   5775: =item scantron_process_corrections
                   5776: 
1.424     albertel 5777:    Gets correction information out of submitted form data and corrects
                   5778:    the scanline
                   5779: 
1.423     albertel 5780: =cut
                   5781: 
1.157     albertel 5782: sub scantron_process_corrections {
                   5783:     my ($r) = @_;
1.257     albertel 5784:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5785:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5786:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5787:     my $which=$env{'form.scantron_line'};
1.200     albertel 5788:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5789:     my ($skip,$err,$errmsg);
1.257     albertel 5790:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5791: 	$skip=1;
1.257     albertel 5792:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5793: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5794: 	    $env{'form.scantron_domain'};
1.157     albertel 5795: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5796: 	($line,$err,$errmsg)=
                   5797: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5798: 				     'ID',{'newid'=>$newid,
1.257     albertel 5799: 				    'username'=>$env{'form.scantron_username'},
                   5800: 				    'domain'=>$env{'form.scantron_domain'}});
                   5801:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5802: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5803: 	my $newCODE;
1.192     albertel 5804: 	my %args;
1.190     albertel 5805: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5806: 	    $newCODE='use_unfound';
1.190     albertel 5807: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5808: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5809: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5810: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5811: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5812: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5813: 	}
1.257     albertel 5814: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5815: 	    $args{'CODE_ignore_dup'}=1;
                   5816: 	}
                   5817: 	$args{'CODE'}=$newCODE;
1.186     albertel 5818: 	($line,$err,$errmsg)=
                   5819: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5820: 				     'CODE',\%args);
1.257     albertel 5821:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5822: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5823: 	    ($line,$err,$errmsg)=
                   5824: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5825: 					 $which,'answer',
                   5826: 					 { 'question'=>$question,
1.503     raeburn  5827: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   5828:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 5829: 	    if ($err) { last; }
                   5830: 	}
                   5831:     }
                   5832:     if ($err) {
1.398     albertel 5833: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5834:     } else {
1.200     albertel 5835: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5836: 	&scantron_putfile($scanlines,$scan_data);
                   5837:     }
                   5838: }
                   5839: 
1.423     albertel 5840: =pod
                   5841: 
                   5842: =item reset_skipping_status
                   5843: 
1.424     albertel 5844:    Forgets the current set of remember skipped scanlines (and thus
                   5845:    reverts back to considering all lines in the
                   5846:    scantron_skipped_<filename> file)
                   5847: 
1.423     albertel 5848: =cut
                   5849: 
1.200     albertel 5850: sub reset_skipping_status {
                   5851:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5852:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5853:     &scantron_putfile(undef,$scan_data);
                   5854: }
                   5855: 
1.423     albertel 5856: =pod
                   5857: 
                   5858: =item start_skipping
                   5859: 
1.424     albertel 5860:    Marks a scanline to be skipped. 
                   5861: 
1.423     albertel 5862: =cut
                   5863: 
1.376     albertel 5864: sub start_skipping {
1.200     albertel 5865:     my ($scan_data,$i)=@_;
                   5866:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5867:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5868: 	$remembered{$i}=2;
                   5869:     } else {
                   5870: 	$remembered{$i}=1;
                   5871:     }
1.200     albertel 5872:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5873: }
                   5874: 
1.423     albertel 5875: =pod
                   5876: 
                   5877: =item should_be_skipped
                   5878: 
1.424     albertel 5879:    Checks whether a scanline should be skipped.
                   5880: 
1.423     albertel 5881: =cut
                   5882: 
1.200     albertel 5883: sub should_be_skipped {
1.376     albertel 5884:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5885:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5886: 	# not redoing old skips
1.376     albertel 5887: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5888: 	return 0;
                   5889:     }
                   5890:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5891: 
                   5892:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5893: 	return 0;
                   5894:     }
1.200     albertel 5895:     return 1;
                   5896: }
                   5897: 
1.423     albertel 5898: =pod
                   5899: 
                   5900: =item remember_current_skipped
                   5901: 
1.424     albertel 5902:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5903:    file and remembers them into scan_data for later use.
                   5904: 
1.423     albertel 5905: =cut
                   5906: 
1.200     albertel 5907: sub remember_current_skipped {
                   5908:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5909:     my %to_remember;
                   5910:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5911: 	if ($scanlines->{'skipped'}[$i]) {
                   5912: 	    $to_remember{$i}=1;
                   5913: 	}
                   5914:     }
1.376     albertel 5915: 
1.200     albertel 5916:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5917:     &scantron_putfile(undef,$scan_data);
                   5918: }
                   5919: 
1.423     albertel 5920: =pod
                   5921: 
                   5922: =item check_for_error
                   5923: 
1.424     albertel 5924:     Checks if there was an error when attempting to remove a specific
                   5925:     scantron_.. bubble sheet data file. Prints out an error if
                   5926:     something went wrong.
                   5927: 
1.423     albertel 5928: =cut
                   5929: 
1.200     albertel 5930: sub check_for_error {
                   5931:     my ($r,$result)=@_;
                   5932:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 5933: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 5934:     }
                   5935: }
1.157     albertel 5936: 
1.423     albertel 5937: =pod
                   5938: 
                   5939: =item scantron_warning_screen
                   5940: 
1.424     albertel 5941:    Interstitial screen to make sure the operator has selected the
                   5942:    correct options before we start the validation phase.
                   5943: 
1.423     albertel 5944: =cut
                   5945: 
1.203     albertel 5946: sub scantron_warning_screen {
                   5947:     my ($button_text)=@_;
1.257     albertel 5948:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5949:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5950:     my $CODElist;
1.284     albertel 5951:     if ($scantron_config{'CODElocation'} &&
                   5952: 	$scantron_config{'CODEstart'} &&
                   5953: 	$scantron_config{'CODElength'}) {
                   5954: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5955: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5956: 	$CODElist=
1.492     albertel 5957: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 5958: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5959:     }
1.492     albertel 5960:     return ('
1.203     albertel 5961: <p>
1.492     albertel 5962: <span class="LC_warning">
                   5963: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 5964: </p>
                   5965: <table>
1.492     albertel 5966: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   5967: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   5968: '.$CODElist.'
1.203     albertel 5969: </table>
                   5970: <br />
1.492     albertel 5971: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   5972: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 5973: 
                   5974: <br />
1.492     albertel 5975: ');
1.203     albertel 5976: }
                   5977: 
1.423     albertel 5978: =pod
                   5979: 
                   5980: =item scantron_do_warning
                   5981: 
1.424     albertel 5982:    Check if the operator has picked something for all required
                   5983:    fields. Error out if something is missing.
                   5984: 
1.423     albertel 5985: =cut
                   5986: 
1.203     albertel 5987: sub scantron_do_warning {
                   5988:     my ($r)=@_;
1.324     albertel 5989:     my ($symb)=&get_symb($r);
1.203     albertel 5990:     if (!$symb) {return '';}
1.324     albertel 5991:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5992:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5993:     if ( $env{'form.selectpage'} eq '' ||
                   5994: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5995: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 5996: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 5997: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 5998: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 5999: 	} 
1.257     albertel 6000: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6001: 	    $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 6002: 	} 
1.257     albertel 6003: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6004: 	    $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 6005: 	} 
                   6006:     } else {
1.265     www      6007: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6008: 	$r->print('
                   6009: '.$warning.'
                   6010: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6011: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6012: ');
1.237     albertel 6013:     }
1.352     albertel 6014:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6015:     return '';
                   6016: }
                   6017: 
1.423     albertel 6018: =pod
                   6019: 
                   6020: =item scantron_form_start
                   6021: 
1.424     albertel 6022:     html hidden input for remembering all selected grading options
                   6023: 
1.423     albertel 6024: =cut
                   6025: 
1.203     albertel 6026: sub scantron_form_start {
                   6027:     my ($max_bubble)=@_;
                   6028:     my $result= <<SCANTRONFORM;
                   6029: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6030:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6031:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6032:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6033:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6034:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6035:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6036:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6037:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6038:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6039: SCANTRONFORM
1.447     foxr     6040: 
                   6041:   my $line = 0;
                   6042:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6043:        my $chunk =
                   6044: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6045:        $chunk .=
                   6046: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6047:        $chunk .= 
                   6048:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6049:        $chunk .=
                   6050:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6051:        $result .= $chunk;
                   6052:        $line++;
                   6053:    }
1.203     albertel 6054:     return $result;
                   6055: }
                   6056: 
1.423     albertel 6057: =pod
                   6058: 
                   6059: =item scantron_validate_file
                   6060: 
1.424     albertel 6061:     Dispatch routine for doing validation of a bubble sheet data file.
                   6062: 
                   6063:     Also processes any necessary information resets that need to
                   6064:     occur before validation begins (ignore previous corrections,
                   6065:     restarting the skipped records processing)
                   6066: 
1.423     albertel 6067: =cut
                   6068: 
1.157     albertel 6069: sub scantron_validate_file {
                   6070:     my ($r) = @_;
1.324     albertel 6071:     my ($symb)=&get_symb($r);
1.157     albertel 6072:     if (!$symb) {return '';}
1.324     albertel 6073:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6074:     
                   6075:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6076:     # them when doing the corrections reset
1.257     albertel 6077:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6078: 	&reset_skipping_status();
                   6079:     }
1.257     albertel 6080:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6081: 	&remember_current_skipped();
1.257     albertel 6082: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6083:     }
                   6084: 
1.257     albertel 6085:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6086: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6087: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6088: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6089: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6090:     }
1.200     albertel 6091: 
1.257     albertel 6092:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6093: 	&scantron_process_corrections($r);
                   6094:     }
1.503     raeburn  6095:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6096:     #get the student pick code ready
                   6097:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 6098:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 6099:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6100:     $r->print($result);
                   6101:     
1.334     albertel 6102:     my @validate_phases=( 'sequence',
                   6103: 			  'ID',
1.157     albertel 6104: 			  'CODE',
                   6105: 			  'doublebubble',
                   6106: 			  'missingbubbles');
1.257     albertel 6107:     if (!$env{'form.validatepass'}) {
                   6108: 	$env{'form.validatepass'} = 0;
1.157     albertel 6109:     }
1.257     albertel 6110:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6111: 
1.448     foxr     6112: 
1.157     albertel 6113:     my $stop=0;
                   6114:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6115: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6116: 	$r->rflush();
                   6117: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6118: 	{
                   6119: 	    no strict 'refs';
                   6120: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6121: 	}
                   6122:     }
                   6123:     if (!$stop) {
1.203     albertel 6124: 	my $warning=&scantron_warning_screen('Start Grading');
1.512     www      6125: 	$r->print(&mt('Validation process complete.').'<br />
1.492     albertel 6126: '.$warning.'
                   6127: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
1.203     albertel 6128: <input type="hidden" name="command" value="scantron_process" />
1.492     albertel 6129: ');
1.203     albertel 6130: 
1.157     albertel 6131:     } else {
                   6132: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6133: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6134:     }
                   6135:     if ($stop) {
1.334     albertel 6136: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.492     albertel 6137: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
                   6138: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6139: 
1.492     albertel 6140: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6141: 	} else {
1.503     raeburn  6142:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
                   6143: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
                   6144:             } else {
                   6145:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
                   6146:             }
1.492     albertel 6147: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6148: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6149: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6150: 	}
1.157     albertel 6151:     }
1.352     albertel 6152:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6153:     return '';
                   6154: }
                   6155: 
1.423     albertel 6156: 
                   6157: =pod
                   6158: 
                   6159: =item scantron_remove_file
                   6160: 
1.424     albertel 6161:    Removes the requested bubble sheet data file, makes sure that
                   6162:    scantron_original_<filename> is never removed
                   6163: 
                   6164: 
1.423     albertel 6165: =cut
                   6166: 
1.200     albertel 6167: sub scantron_remove_file {
1.192     albertel 6168:     my ($which)=@_;
1.257     albertel 6169:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6170:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6171:     my $file='scantron_';
1.200     albertel 6172:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6173: 	$file.=$which.'_';
1.192     albertel 6174:     } else {
                   6175: 	return 'refused';
                   6176:     }
1.257     albertel 6177:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6178:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6179: }
                   6180: 
1.423     albertel 6181: 
                   6182: =pod
                   6183: 
                   6184: =item scantron_remove_scan_data
                   6185: 
1.424     albertel 6186:    Removes all scan_data correction for the requested bubble sheet
                   6187:    data file.  (In the case that both the are doing skipped records we need
                   6188:    to remember the old skipped lines for the time being so that element
                   6189:    persists for a while.)
                   6190: 
1.423     albertel 6191: =cut
                   6192: 
1.200     albertel 6193: sub scantron_remove_scan_data {
1.257     albertel 6194:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6195:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6196:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6197:     my @todelete;
1.257     albertel 6198:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6199:     foreach my $key (@keys) {
                   6200: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6201: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6202: 		$key=~/remember_skipping/) {
                   6203: 		next;
                   6204: 	    }
1.192     albertel 6205: 	    push(@todelete,$key);
                   6206: 	}
                   6207:     }
1.200     albertel 6208:     my $result;
1.192     albertel 6209:     if (@todelete) {
1.491     albertel 6210: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6211: 				       \@todelete,$cdom,$cname);
                   6212:     } else {
                   6213: 	$result = 'ok';
1.192     albertel 6214:     }
                   6215:     return $result;
                   6216: }
                   6217: 
1.423     albertel 6218: 
                   6219: =pod
                   6220: 
                   6221: =item scantron_getfile
                   6222: 
1.424     albertel 6223:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6224:     the scan_data hash
                   6225:   
                   6226:   Arguments:
                   6227:     None
                   6228: 
                   6229:   Returns:
                   6230:     2 hash references
                   6231: 
                   6232:      - first one has 
                   6233:          orig      -
                   6234:          corrected -
                   6235:          skipped   -  each of which points to an array ref of the specified
                   6236:                       file broken up into individual lines
                   6237:          count     - number of scanlines
                   6238:  
                   6239:      - second is the scan_data hash possible keys are
1.425     albertel 6240:        ($number refers to scanline numbered $number and thus the key affects
                   6241:         only that scanline
                   6242:         $bubline refers to the specific bubble line element and the aspects
                   6243:         refers to that specific bubble line element)
                   6244: 
                   6245:        $number.user - username:domain to use
                   6246:        $number.CODE_ignore_dup 
                   6247:                     - ignore the duplicate CODE error 
                   6248:        $number.useCODE
                   6249:                     - use the CODE in the scanline as is
                   6250:        $number.no_bubble.$bubline
                   6251:                     - it is valid that there is no bubbled in bubble
                   6252:                       at $number $bubline
                   6253:        remember_skipping
                   6254:                     - a frozen hash containing keys of $number and values
                   6255:                       of either 
                   6256:                         1 - we are on a 'do skipped records pass' and plan
                   6257:                             on processing this line
                   6258:                         2 - we are on a 'do skipped records pass' and this
                   6259:                             scanline has been marked to skip yet again
1.424     albertel 6260: 
1.423     albertel 6261: =cut
                   6262: 
1.157     albertel 6263: sub scantron_getfile {
1.200     albertel 6264:     #FIXME really would prefer a scantron directory
1.257     albertel 6265:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6266:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6267:     my $lines;
                   6268:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6269: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6270:     my %scanlines;
                   6271:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6272:     my $temp=$scanlines{'orig'};
                   6273:     $scanlines{'count'}=$#$temp;
                   6274: 
                   6275:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6276: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6277:     if ($lines eq '-1') {
                   6278: 	$scanlines{'corrected'}=[];
                   6279:     } else {
                   6280: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6281:     }
                   6282:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6283: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6284:     if ($lines eq '-1') {
                   6285: 	$scanlines{'skipped'}=[];
                   6286:     } else {
                   6287: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6288:     }
1.175     albertel 6289:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6290:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6291:     my %scan_data = @tmp;
                   6292:     return (\%scanlines,\%scan_data);
                   6293: }
                   6294: 
1.423     albertel 6295: =pod
                   6296: 
                   6297: =item lonnet_putfile
                   6298: 
1.424     albertel 6299:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6300: 
                   6301:  Arguments:
                   6302:    $contents - data to store
                   6303:    $filename - filename to store $contents into
                   6304: 
                   6305:  Returns:
                   6306:    result value from &Apache::lonnet::finishuserfileupload
                   6307: 
1.423     albertel 6308: =cut
                   6309: 
1.157     albertel 6310: sub lonnet_putfile {
                   6311:     my ($contents,$filename)=@_;
1.257     albertel 6312:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6313:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6314:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6315:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6316: 
                   6317: }
                   6318: 
1.423     albertel 6319: =pod
                   6320: 
                   6321: =item scantron_putfile
                   6322: 
1.424     albertel 6323:     Stores the current version of the bubble sheet data files, and the
                   6324:     scan_data hash. (Does not modify the original version only the
                   6325:     corrected and skipped versions.
                   6326: 
                   6327:  Arguments:
                   6328:     $scanlines - hash ref that looks like the first return value from
                   6329:                  &scantron_getfile()
                   6330:     $scan_data - hash ref that looks like the second return value from
                   6331:                  &scantron_getfile()
                   6332: 
1.423     albertel 6333: =cut
                   6334: 
1.157     albertel 6335: sub scantron_putfile {
                   6336:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6337:     #FIXME really would prefer a scantron directory
1.257     albertel 6338:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6339:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6340:     if ($scanlines) {
                   6341: 	my $prefix='scantron_';
1.157     albertel 6342: # no need to update orig, shouldn't change
                   6343: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6344: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6345: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6346: 			$prefix.'corrected_'.
1.257     albertel 6347: 			$env{'form.scantron_selectfile'});
1.200     albertel 6348: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6349: 			$prefix.'skipped_'.
1.257     albertel 6350: 			$env{'form.scantron_selectfile'});
1.200     albertel 6351:     }
1.175     albertel 6352:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6353: }
                   6354: 
1.423     albertel 6355: =pod
                   6356: 
                   6357: =item scantron_get_line
                   6358: 
1.424     albertel 6359:    Returns the correct version of the scanline
                   6360: 
                   6361:  Arguments:
                   6362:     $scanlines - hash ref that looks like the first return value from
                   6363:                  &scantron_getfile()
                   6364:     $scan_data - hash ref that looks like the second return value from
                   6365:                  &scantron_getfile()
                   6366:     $i         - number of the requested line (starts at 0)
                   6367: 
                   6368:  Returns:
                   6369:    A scanline, (either the original or the corrected one if it
                   6370:    exists), or undef if the requested scanline should be
                   6371:    skipped. (Either because it's an skipped scanline, or it's an
                   6372:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6373:    pass.
                   6374: 
1.423     albertel 6375: =cut
                   6376: 
1.157     albertel 6377: sub scantron_get_line {
1.200     albertel 6378:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6379:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6380:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6381:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6382:     return $scanlines->{'orig'}[$i]; 
                   6383: }
                   6384: 
1.423     albertel 6385: =pod
                   6386: 
                   6387: =item scantron_todo_count
                   6388: 
1.424     albertel 6389:     Counts the number of scanlines that need processing.
                   6390: 
                   6391:  Arguments:
                   6392:     $scanlines - hash ref that looks like the first return value from
                   6393:                  &scantron_getfile()
                   6394:     $scan_data - hash ref that looks like the second return value from
                   6395:                  &scantron_getfile()
                   6396: 
                   6397:  Returns:
                   6398:     $count - number of scanlines to process
                   6399: 
1.423     albertel 6400: =cut
                   6401: 
1.200     albertel 6402: sub get_todo_count {
                   6403:     my ($scanlines,$scan_data)=@_;
                   6404:     my $count=0;
                   6405:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6406: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6407: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6408: 	$count++;
                   6409:     }
                   6410:     return $count;
                   6411: }
                   6412: 
1.423     albertel 6413: =pod
                   6414: 
                   6415: =item scantron_put_line
                   6416: 
1.424     albertel 6417:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6418:     data file.
                   6419: 
                   6420:  Arguments:
                   6421:     $scanlines - hash ref that looks like the first return value from
                   6422:                  &scantron_getfile()
                   6423:     $scan_data - hash ref that looks like the second return value from
                   6424:                  &scantron_getfile()
                   6425:     $i         - line number to update
                   6426:     $newline   - contents of the updated scanline
                   6427:     $skip      - if true make the line for skipping and update the
                   6428:                  'skipped' file
                   6429: 
1.423     albertel 6430: =cut
                   6431: 
1.157     albertel 6432: sub scantron_put_line {
1.200     albertel 6433:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6434:     if ($skip) {
                   6435: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6436: 	&start_skipping($scan_data,$i);
1.157     albertel 6437: 	return;
                   6438:     }
                   6439:     $scanlines->{'corrected'}[$i]=$newline;
                   6440: }
                   6441: 
1.423     albertel 6442: =pod
                   6443: 
                   6444: =item scantron_clear_skip
                   6445: 
1.424     albertel 6446:    Remove a line from the 'skipped' file
                   6447: 
                   6448:  Arguments:
                   6449:     $scanlines - hash ref that looks like the first return value from
                   6450:                  &scantron_getfile()
                   6451:     $scan_data - hash ref that looks like the second return value from
                   6452:                  &scantron_getfile()
                   6453:     $i         - line number to update
                   6454: 
1.423     albertel 6455: =cut
                   6456: 
1.376     albertel 6457: sub scantron_clear_skip {
                   6458:     my ($scanlines,$scan_data,$i)=@_;
                   6459:     if (exists($scanlines->{'skipped'}[$i])) {
                   6460: 	undef($scanlines->{'skipped'}[$i]);
                   6461: 	return 1;
                   6462:     }
                   6463:     return 0;
                   6464: }
                   6465: 
1.423     albertel 6466: =pod
                   6467: 
                   6468: =item scantron_filter_not_exam
                   6469: 
1.424     albertel 6470:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6471:    filter out resources that are not marked as 'exam' mode
                   6472: 
1.423     albertel 6473: =cut
                   6474: 
1.334     albertel 6475: sub scantron_filter_not_exam {
                   6476:     my ($curres)=@_;
                   6477:     
                   6478:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6479: 	# if the user has asked to not have either hidden
                   6480: 	# or 'randomout' controlled resources to be graded
                   6481: 	# don't include them
                   6482: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6483: 	    && $curres->randomout) {
                   6484: 	    return 0;
                   6485: 	}
                   6486: 	return 1;
                   6487:     }
                   6488:     return 0;
                   6489: }
                   6490: 
1.423     albertel 6491: =pod
                   6492: 
                   6493: =item scantron_validate_sequence
                   6494: 
1.424     albertel 6495:     Validates the selected sequence, checking for resource that are
                   6496:     not set to exam mode.
                   6497: 
1.423     albertel 6498: =cut
                   6499: 
1.334     albertel 6500: sub scantron_validate_sequence {
                   6501:     my ($r,$currentphase) = @_;
                   6502: 
                   6503:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6504:     my (undef,undef,$sequence)=
                   6505: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6506: 
                   6507:     my $map=$navmap->getResourceByUrl($sequence);
                   6508: 
                   6509:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6510:                                     value="ignore" />');
                   6511:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6512: 	my @resources=
                   6513: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6514: 	if (@resources) {
1.357     banghart 6515: 	    $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 6516: 	    return (1,$currentphase);
                   6517: 	}
                   6518:     }
                   6519: 
                   6520:     return (0,$currentphase+1);
                   6521: }
                   6522: 
1.423     albertel 6523: =pod
                   6524: 
                   6525: =item scantron_validate_ID
                   6526: 
1.424     albertel 6527:    Validates all scanlines in the selected file to not have any
                   6528:    invalid or underspecified student IDs
                   6529: 
1.423     albertel 6530: =cut
                   6531: 
1.157     albertel 6532: sub scantron_validate_ID {
                   6533:     my ($r,$currentphase) = @_;
                   6534:     
                   6535:     #get student info
                   6536:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6537:     my %idmap=&username_to_idmap($classlist);
                   6538: 
                   6539:     #get scantron line setup
1.257     albertel 6540:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6541:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6542:     
                   6543:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6544: 
                   6545:     my %found=('ids'=>{},'usernames'=>{});
                   6546:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6547: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6548: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6549: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6550: 						 $scan_data);
                   6551: 	my $id=$$scan_record{'scantron.ID'};
                   6552: 	my $found;
                   6553: 	foreach my $checkid (keys(%idmap)) {
                   6554: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6555: 	}
                   6556: 	if ($found) {
                   6557: 	    my $username=$idmap{$found};
                   6558: 	    if ($found{'ids'}{$found}) {
                   6559: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6560: 					 $line,'duplicateID',$found);
1.194     albertel 6561: 		return(1,$currentphase);
1.157     albertel 6562: 	    } elsif ($found{'usernames'}{$username}) {
                   6563: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6564: 					 $line,'duplicateID',$username);
1.194     albertel 6565: 		return(1,$currentphase);
1.157     albertel 6566: 	    }
1.186     albertel 6567: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6568: 	    $found{'ids'}{$found}++;
                   6569: 	    $found{'usernames'}{$username}++;
                   6570: 	} else {
                   6571: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6572: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6573: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6574: 		    &scantron_get_correction($r,$i,$scan_record,
                   6575: 					     \%scantron_config,
                   6576: 					     $line,'duplicateID',$username);
1.194     albertel 6577: 		    return(1,$currentphase);
1.157     albertel 6578: 		} elsif (!defined($username)) {
                   6579: 		    &scantron_get_correction($r,$i,$scan_record,
                   6580: 					     \%scantron_config,
                   6581: 					     $line,'incorrectID');
1.194     albertel 6582: 		    return(1,$currentphase);
1.157     albertel 6583: 		}
                   6584: 		$found{'usernames'}{$username}++;
                   6585: 	    } else {
                   6586: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6587: 					 $line,'incorrectID');
1.194     albertel 6588: 		return(1,$currentphase);
1.157     albertel 6589: 	    }
                   6590: 	}
                   6591:     }
                   6592: 
                   6593:     return (0,$currentphase+1);
                   6594: }
                   6595: 
1.423     albertel 6596: =pod
                   6597: 
                   6598: =item scantron_get_correction
                   6599: 
1.424     albertel 6600:    Builds the interface screen to interact with the operator to fix a
                   6601:    specific error condition in a specific scanline
                   6602: 
                   6603:  Arguments:
                   6604:     $r           - Apache request object
                   6605:     $i           - number of the current scanline
                   6606:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6607:     $scan_config - hash ref as returned from &get_scantron_config()
                   6608:     $line        - full contents of the current scanline
                   6609:     $error       - error condition, valid values are
                   6610:                    'incorrectCODE', 'duplicateCODE',
                   6611:                    'doublebubble', 'missingbubble',
                   6612:                    'duplicateID', 'incorrectID'
                   6613:     $arg         - extra information needed
                   6614:        For errors:
                   6615:          - duplicateID   - paper number that this studentID was seen before on
                   6616:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6617:                            seen on before
                   6618:          - incorrectCODE - current incorrect CODE 
                   6619:          - doublebubble  - array ref of the bubble lines that have double
                   6620:                            bubble errors
                   6621:          - missingbubble - array ref of the bubble lines that have missing
                   6622:                            bubble errors
                   6623: 
1.423     albertel 6624: =cut
                   6625: 
1.157     albertel 6626: sub scantron_get_correction {
                   6627:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6628: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6629: #to show both the current line and the previous one and allow skipping
                   6630: #the previous one or the current one
                   6631: 
1.333     albertel 6632:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6633: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6634: 			    " for PaperID <tt>[_1]</tt>",
                   6635: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6636:     } else {
1.492     albertel 6637: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6638: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6639: 			    $i,$line)."</p> \n");
                   6640:     }
                   6641:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6642: 			  "The name on the paper is [_2],[_3]",
                   6643: 			  $$scan_record{'scantron.ID'},
                   6644: 			  $$scan_record{'scantron.LastName'},
                   6645: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6646: 
1.157     albertel 6647:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6648:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6649:                            # Array populated for doublebubble or
                   6650:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6651:                            # to validate radio button checking   
                   6652: 
1.157     albertel 6653:     if ($error =~ /ID$/) {
1.186     albertel 6654: 	if ($error eq 'incorrectID') {
1.492     albertel 6655: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6656: 		      "</p>\n");
1.157     albertel 6657: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6658: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6659: 	}
1.242     albertel 6660: 	$r->print($message);
1.492     albertel 6661: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6662: 	$r->print("\n<ul><li> ");
                   6663: 	#FIXME it would be nice if this sent back the user ID and
                   6664: 	#could do partial userID matches
                   6665: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6666: 				       'scantron_username','scantron_domain'));
                   6667: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6668: 	$r->print("\n@".
1.257     albertel 6669: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6670: 
                   6671: 	$r->print('</li>');
1.186     albertel 6672:     } elsif ($error =~ /CODE$/) {
                   6673: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6674: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6675: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6676: 	    $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 6677: 	}
1.492     albertel 6678: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6679: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6680: 	$r->print($message);
1.492     albertel 6681: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6682: 	$r->print("\n<br /> ");
1.194     albertel 6683: 	my $i=0;
1.273     albertel 6684: 	if ($error eq 'incorrectCODE' 
                   6685: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6686: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6687: 	    if ($closest > 0) {
                   6688: 		foreach my $testcode (@{$closest}) {
                   6689: 		    my $checked='';
1.401     albertel 6690: 		    if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6691: 		    $r->print("
                   6692:    <label>
                   6693:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
                   6694:        ".&mt("Use the similar CODE [_1] instead.",
                   6695: 	    "<b><tt>".$testcode."</tt></b>")."
                   6696:     </label>
                   6697:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6698: 		    $r->print("\n<br />");
                   6699: 		    $i++;
                   6700: 		}
1.194     albertel 6701: 	    }
                   6702: 	}
1.273     albertel 6703: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6704: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6705: 	    $r->print("
                   6706:     <label>
                   6707:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
                   6708:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6709: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6710:     </label>");
1.273     albertel 6711: 	    $r->print("\n<br />");
                   6712: 	}
1.194     albertel 6713: 
1.188     albertel 6714: 	$r->print(<<ENDSCRIPT);
                   6715: <script type="text/javascript">
                   6716: function change_radio(field) {
1.190     albertel 6717:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6718:     var i;
                   6719:     for (i=0;i<slct.length;i++) {
                   6720:         if (slct[i].value==field) { slct[i].checked=true; }
                   6721:     }
                   6722: }
                   6723: </script>
                   6724: ENDSCRIPT
1.187     albertel 6725: 	my $href="/adm/pickcode?".
1.359     www      6726: 	   "form=".&escape("scantronupload").
                   6727: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6728: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6729: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6730: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6731: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6732: 	    $r->print("
                   6733:     <label>
                   6734:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6735:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6736: 	     "<a target='_blank' href='$href'>","</a>")."
                   6737:     </label> 
                   6738:     ".&mt("Selected CODE is [_1]","<input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />"));
1.332     albertel 6739: 	    $r->print("\n<br />");
                   6740: 	}
1.492     albertel 6741: 	$r->print("
                   6742:     <label>
                   6743:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6744:        ".&mt("Use [_1] as the CODE.",
                   6745: 	     "</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 6746: 	$r->print("\n<br /><br />");
1.157     albertel 6747:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6748: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6749: 
                   6750: 	# The form field scantron_questions is acutally a list of line numbers.
                   6751: 	# represented by this form so:
                   6752: 
                   6753: 	my $line_list = &questions_to_line_list($arg);
                   6754: 
1.157     albertel 6755: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6756: 		  $line_list.'" />');
1.242     albertel 6757: 	$r->print($message);
1.492     albertel 6758: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6759: 	foreach my $question (@{$arg}) {
1.503     raeburn  6760: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6761:                                                    $scan_record, $error);
                   6762:             push (@lines_to_correct,@linenums);
1.157     albertel 6763: 	}
1.503     raeburn  6764:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6765:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6766: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6767: 	$r->print($message);
1.492     albertel 6768: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6769: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6770: 
1.503     raeburn  6771: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6772: 	# a list of question numbers. Therefore:
                   6773: 	#
                   6774: 	
                   6775: 	my $line_list = &questions_to_line_list($arg);
                   6776: 
1.157     albertel 6777: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6778: 		  $line_list.'" />');
1.157     albertel 6779: 	foreach my $question (@{$arg}) {
1.503     raeburn  6780: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6781:                                                    $scan_record, $error);
                   6782:             push (@lines_to_correct,@linenums);
1.157     albertel 6783: 	}
1.503     raeburn  6784:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6785:     } else {
                   6786: 	$r->print("\n<ul>");
                   6787:     }
                   6788:     $r->print("\n</li></ul>");
1.497     foxr     6789: }
                   6790: 
1.503     raeburn  6791: sub verify_bubbles_checked {
                   6792:     my (@ansnums) = @_;
                   6793:     my $ansnumstr = join('","',@ansnums);
                   6794:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6795:     my $output = (<<ENDSCRIPT);
                   6796: <script type="text/javascript">
                   6797: function verify_bubble_radio(form) {
                   6798:     var ansnumArray = new Array ("$ansnumstr");
                   6799:     var need_bubble_count = 0;
                   6800:     for (var i=0; i<ansnumArray.length; i++) {
                   6801:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6802:             var bubble_picked = 0; 
                   6803:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6804:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6805:                     bubble_picked = 1;
                   6806:                 }
                   6807:             }
                   6808:             if (bubble_picked == 0) {
                   6809:                 need_bubble_count ++;
                   6810:             }
                   6811:         }
                   6812:     }
                   6813:     if (need_bubble_count) {
                   6814:         alert("$warning");
                   6815:         return;
                   6816:     }
                   6817:     form.submit(); 
                   6818: }
                   6819: </script>
                   6820: ENDSCRIPT
                   6821:     return $output;
                   6822: }
                   6823: 
1.497     foxr     6824: =pod
                   6825: 
                   6826: =item  questions_to_line_list
1.157     albertel 6827: 
1.497     foxr     6828: Converts a list of questions into a string of comma separated
                   6829: line numbers in the answer sheet used by the questions.  This is
                   6830: used to fill in the scantron_questions form field.
                   6831: 
                   6832:   Arguments:
                   6833:      questions    - Reference to an array of questions.
                   6834: 
                   6835: =cut
                   6836: 
                   6837: 
                   6838: sub questions_to_line_list {
                   6839:     my ($questions) = @_;
                   6840:     my @lines;
                   6841: 
1.503     raeburn  6842:     foreach my $item (@{$questions}) {
                   6843:         my $question = $item;
                   6844:         my ($first,$count,$last);
                   6845:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   6846:             $question = $1;
                   6847:             my $subquestion = $2;
                   6848:             $first = $first_bubble_line{$question-1} + 1;
                   6849:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6850:             my $subcount = 1;
                   6851:             while ($subcount<$subquestion) {
                   6852:                 $first += $subans[$subcount-1];
                   6853:                 $subcount ++;
                   6854:             }
                   6855:             $count = $subans[$subquestion-1];
                   6856:         } else {
                   6857: 	    $first   = $first_bubble_line{$question-1} + 1;
                   6858: 	    $count   = $bubble_lines_per_response{$question-1};
                   6859:         }
1.506     raeburn  6860:         $last = $first+$count-1;
1.503     raeburn  6861:         push(@lines, ($first..$last));
1.497     foxr     6862:     }
                   6863:     return join(',', @lines);
                   6864: }
                   6865: 
                   6866: =pod 
                   6867: 
                   6868: =item prompt_for_corrections
                   6869: 
                   6870: Prompts for a potentially multiline correction to the
                   6871: user's bubbling (factors out common code from scantron_get_correction
                   6872: for multi and missing bubble cases).
                   6873: 
                   6874:  Arguments:
                   6875:    $r           - Apache request object.
                   6876:    $question    - The question number to prompt for.
                   6877:    $scan_config - The scantron file configuration hash.
                   6878:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  6879:    $error       - Type of error
1.497     foxr     6880: 
                   6881:  Implicit inputs:
                   6882:    %bubble_lines_per_response   - Starting line numbers for each question.
                   6883:                                   Numbered from 0 (but question numbers are from
                   6884:                                   1.
                   6885:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  6886:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   6887:                                   type problems render as separate sub-questions, 
1.503     raeburn  6888:                                   in exam mode. This hash contains a 
                   6889:                                   comma-separated list of the lines per 
                   6890:                                   sub-question.
1.510     raeburn  6891:    %responsetype_per_response   - essayresponse, formularesponse,
                   6892:                                   stringresponse, imageresponse, reactionresponse,
                   6893:                                   and organicresponse type problem parts can have
1.503     raeburn  6894:                                   multiple lines per response if the weight
                   6895:                                   assigned exceeds 10.  In this case, only
                   6896:                                   one bubble per line is permitted, but more 
                   6897:                                   than one line might contain bubbles, e.g.
                   6898:                                   bubbling of: line 1 - J, line 2 - J, 
                   6899:                                   line 3 - B would assign 22 points.  
1.497     foxr     6900: 
                   6901: =cut
                   6902: 
                   6903: sub prompt_for_corrections {
1.503     raeburn  6904:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   6905:     my ($current_line,$lines);
                   6906:     my @linenums;
                   6907:     my $questionnum = $question;
                   6908:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   6909:         $question = $1;
                   6910:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   6911:         my $subquestion = $2;
                   6912:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6913:         my $subcount = 1;
                   6914:         while ($subcount<$subquestion) {
                   6915:             $current_line += $subans[$subcount-1];
                   6916:             $subcount ++;
                   6917:         }
                   6918:         $lines = $subans[$subquestion-1];
                   6919:     } else {
                   6920:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   6921:         $lines        = $bubble_lines_per_response{$question-1};
                   6922:     }
1.497     foxr     6923:     if ($lines > 1) {
1.503     raeburn  6924:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   6925:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   6926:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  6927:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   6928:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   6929:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   6930:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.503     raeburn  6931:             $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 />');
                   6932:         } else {
                   6933:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   6934:         }
1.497     foxr     6935:     }
                   6936:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  6937:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   6938: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   6939: 	        		  $questionnum,$error,split('', $selected));
                   6940:         push (@linenums,$current_line);
1.497     foxr     6941: 	$current_line++;
                   6942:     }
                   6943:     if ($lines > 1) {
                   6944: 	$r->print("<hr /><br />");
                   6945:     }
1.503     raeburn  6946:     return @linenums;
1.157     albertel 6947: }
1.423     albertel 6948: 
                   6949: =pod
                   6950: 
                   6951: =item scantron_bubble_selector
                   6952:   
                   6953:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6954:    possibly showing the existing the selected bubbles if known
1.423     albertel 6955: 
                   6956:  Arguments:
                   6957:     $r           - Apache request object
                   6958:     $scan_config - hash from &get_scantron_config()
1.497     foxr     6959:     $line        - Number of the line being displayed.
1.503     raeburn  6960:     $questionnum - Question number (may include subquestion)
                   6961:     $error       - Type of error.
1.497     foxr     6962:     @selected    - Array of bubbles picked on this line.
1.423     albertel 6963: 
                   6964: =cut
                   6965: 
1.157     albertel 6966: sub scantron_bubble_selector {
1.503     raeburn  6967:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 6968:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6969: 
                   6970:     my $scmode=$$scan_config{'Qon'};
                   6971:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6972: 
1.157     albertel 6973:     my @alphabet=('A'..'Z');
1.503     raeburn  6974:     $r->print(&Apache::loncommon::start_data_table().
                   6975:               &Apache::loncommon::start_data_table_row());
                   6976:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     6977:     for (my $i=0;$i<$max+1;$i++) {
                   6978: 	$r->print("\n".'<td align="center">');
                   6979: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   6980: 	else { $r->print('&nbsp;'); }
                   6981: 	$r->print('</td>');
                   6982:     }
1.503     raeburn  6983:     $r->print(&Apache::loncommon::end_data_table_row().
                   6984:               &Apache::loncommon::start_data_table_row());
1.497     foxr     6985:     for (my $i=0;$i<$max;$i++) {
                   6986: 	$r->print("\n".
                   6987: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6988: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6989:     }
1.503     raeburn  6990:     my $nobub_checked = ' ';
                   6991:     if ($error eq 'missingbubble') {
                   6992:         $nobub_checked = ' checked = "checked" ';
                   6993:     }
                   6994:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   6995: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   6996:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   6997:               $line.'" value="'.$questionnum.'" /></td>');
                   6998:     $r->print(&Apache::loncommon::end_data_table_row().
                   6999:               &Apache::loncommon::end_data_table());
1.157     albertel 7000: }
                   7001: 
1.423     albertel 7002: =pod
                   7003: 
                   7004: =item num_matches
                   7005: 
1.424     albertel 7006:    Counts the number of characters that are the same between the two arguments.
                   7007: 
                   7008:  Arguments:
                   7009:    $orig - CODE from the scanline
                   7010:    $code - CODE to match against
                   7011: 
                   7012:  Returns:
                   7013:    $count - integer count of the number of same characters between the
                   7014:             two arguments
                   7015: 
1.423     albertel 7016: =cut
                   7017: 
1.194     albertel 7018: sub num_matches {
                   7019:     my ($orig,$code) = @_;
                   7020:     my @code=split(//,$code);
                   7021:     my @orig=split(//,$orig);
                   7022:     my $same=0;
                   7023:     for (my $i=0;$i<scalar(@code);$i++) {
                   7024: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7025:     }
                   7026:     return $same;
                   7027: }
                   7028: 
1.423     albertel 7029: =pod
                   7030: 
                   7031: =item scantron_get_closely_matching_CODEs
                   7032: 
1.424     albertel 7033:    Cycles through all CODEs and finds the set that has the greatest
                   7034:    number of same characters as the provided CODE
                   7035: 
                   7036:  Arguments:
                   7037:    $allcodes - hash ref returned by &get_codes()
                   7038:    $CODE     - CODE from the current scanline
                   7039: 
                   7040:  Returns:
                   7041:    2 element list
                   7042:     - first elements is number of how closely matching the best fit is 
                   7043:       (5 means best set has 5 matching characters)
                   7044:     - second element is an arrary ref containing the set of valid CODEs
                   7045:       that best fit the passed in CODE
                   7046: 
1.423     albertel 7047: =cut
                   7048: 
1.194     albertel 7049: sub scantron_get_closely_matching_CODEs {
                   7050:     my ($allcodes,$CODE)=@_;
                   7051:     my @CODEs;
                   7052:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7053: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7054:     }
                   7055: 
                   7056:     return ($#CODEs,$CODEs[-1]);
                   7057: }
                   7058: 
1.423     albertel 7059: =pod
                   7060: 
                   7061: =item get_codes
                   7062: 
1.424     albertel 7063:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7064:    set of remembered CODEs.
                   7065: 
                   7066:  Arguments:
                   7067:   $old_name - name of the set of remembered CODEs
                   7068:   $cdom     - domain of the course
                   7069:   $cnum     - internal course name
                   7070: 
                   7071:  Returns:
                   7072:   %allcodes - keys are the valid CODEs, values are all 1
                   7073: 
1.423     albertel 7074: =cut
                   7075: 
1.194     albertel 7076: sub get_codes {
1.280     foxr     7077:     my ($old_name, $cdom, $cnum) = @_;
                   7078:     if (!$old_name) {
                   7079: 	$old_name=$env{'form.scantron_CODElist'};
                   7080:     }
                   7081:     if (!$cdom) {
                   7082: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7083:     }
                   7084:     if (!$cnum) {
                   7085: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7086:     }
1.278     albertel 7087:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7088: 				    $cdom,$cnum);
                   7089:     my %allcodes;
                   7090:     if ($result{"type\0$old_name"} eq 'number') {
                   7091: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7092:     } else {
                   7093: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7094:     }
1.194     albertel 7095:     return %allcodes;
                   7096: }
                   7097: 
1.423     albertel 7098: =pod
                   7099: 
                   7100: =item scantron_validate_CODE
                   7101: 
1.424     albertel 7102:    Validates all scanlines in the selected file to not have any
                   7103:    invalid or underspecified CODEs and that none of the codes are
                   7104:    duplicated if this was requested.
                   7105: 
1.423     albertel 7106: =cut
                   7107: 
1.157     albertel 7108: sub scantron_validate_CODE {
                   7109:     my ($r,$currentphase) = @_;
1.257     albertel 7110:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7111:     if ($scantron_config{'CODElocation'} &&
                   7112: 	$scantron_config{'CODEstart'} &&
                   7113: 	$scantron_config{'CODElength'}) {
1.257     albertel 7114: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7115: 	    &FIXME_blow_up()
                   7116: 	}
                   7117:     } else {
                   7118: 	return (0,$currentphase+1);
                   7119:     }
                   7120:     
                   7121:     my %usedCODEs;
                   7122: 
1.194     albertel 7123:     my %allcodes=&get_codes();
1.186     albertel 7124: 
1.447     foxr     7125:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   7126: 
1.186     albertel 7127:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7128:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7129: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7130: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7131: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7132: 						 $scan_data);
                   7133: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7134: 	my $error=0;
1.224     albertel 7135: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7136: 	    &scantron_get_correction($r,$i,$scan_record,
                   7137: 				     \%scantron_config,
                   7138: 				     $line,'incorrectCODE',\%allcodes);
                   7139: 	    return(1,$currentphase);
                   7140: 	}
1.221     albertel 7141: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7142: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7143: 	    &scantron_get_correction($r,$i,$scan_record,
                   7144: 				     \%scantron_config,
1.194     albertel 7145: 				     $line,'incorrectCODE',\%allcodes);
                   7146: 	    return(1,$currentphase);
1.186     albertel 7147: 	}
1.214     albertel 7148: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7149: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7150: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7151: 	    &scantron_get_correction($r,$i,$scan_record,
                   7152: 				     \%scantron_config,
1.194     albertel 7153: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7154: 	    return(1,$currentphase);
1.186     albertel 7155: 	}
1.194     albertel 7156: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7157:     }
1.157     albertel 7158:     return (0,$currentphase+1);
                   7159: }
                   7160: 
1.423     albertel 7161: =pod
                   7162: 
                   7163: =item scantron_validate_doublebubble
                   7164: 
1.424     albertel 7165:    Validates all scanlines in the selected file to not have any
                   7166:    bubble lines with multiple bubbles marked.
                   7167: 
1.423     albertel 7168: =cut
                   7169: 
1.157     albertel 7170: sub scantron_validate_doublebubble {
                   7171:     my ($r,$currentphase) = @_;
                   7172:     #get student info
                   7173:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7174:     my %idmap=&username_to_idmap($classlist);
                   7175: 
                   7176:     #get scantron line setup
1.257     albertel 7177:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7178:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     7179:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   7180: 
1.157     albertel 7181:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7182: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7183: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7184: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7185: 						 $scan_data);
                   7186: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7187: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7188: 				 'doublebubble',
                   7189: 				 $$scan_record{'scantron.doubleerror'});
                   7190:     	return (1,$currentphase);
                   7191:     }
                   7192:     return (0,$currentphase+1);
                   7193: }
                   7194: 
1.423     albertel 7195: =pod
                   7196: 
                   7197: =item scantron_get_maxbubble
                   7198: 
1.424     albertel 7199:    Returns the maximum number of bubble lines that are expected to
                   7200:    occur. Does this by walking the selected sequence rendering the
                   7201:    resource and then checking &Apache::lonxml::get_problem_counter()
                   7202:    for what the current value of the problem counter is.
                   7203: 
1.447     foxr     7204:    Caches the results to $env{'form.scantron_maxbubble'},
1.503     raeburn  7205:    $env{'form.scantron.bubble_lines.n'}, 
                   7206:    $env{'form.scantron.first_bubble_line.n'} and
                   7207:    $env{"form.scantron.sub_bubblelines.n"}
1.447     foxr     7208:    which are the total number of bubble, lines, the number of bubble
1.503     raeburn  7209:    lines for response n and number of the first bubble line for response n,
                   7210:    and a comma separated list of numbers of bubble lines for sub-questions
1.509     raeburn  7211:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
1.424     albertel 7212: 
1.423     albertel 7213: =cut
                   7214: 
1.503     raeburn  7215: sub scantron_get_maxbubble {
1.257     albertel 7216:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7217: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7218: 	&restore_bubble_lines();
1.257     albertel 7219: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7220:     }
1.330     albertel 7221: 
1.447     foxr     7222:     my (undef, undef, $sequence) =
1.257     albertel 7223: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7224: 
1.447     foxr     7225:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 7226:     my $map=$navmap->getResourceByUrl($sequence);
                   7227:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7228: 
                   7229:     &Apache::lonxml::clear_problem_counter();
                   7230: 
1.435     foxr     7231:     my $uname       = $env{'form.student'};
                   7232:     my $udom        = $env{'form.userdom'};
                   7233:     my $cid         = $env{'request.course.id'};
                   7234:     my $total_lines = 0;
                   7235:     %bubble_lines_per_response = ();
1.447     foxr     7236:     %first_bubble_line         = ();
1.503     raeburn  7237:     %subdivided_bubble_lines   = ();
                   7238:     %responsetype_per_response = ();
1.447     foxr     7239:   
                   7240:     my $response_number = 0;
                   7241:     my $bubble_line     = 0;
1.191     albertel 7242:     foreach my $resource (@resources) {
1.513.2.1  raeburn  7243:         my $symb = $resource->symb();
1.510     raeburn  7244:         # Need to retrieve part IDs and response IDs because essayresponse,
                   7245:         # reactionresponse and organicresponse items are not included in 
                   7246:         # $analysis{'parts'} from lonnet::ssi.  
1.503     raeburn  7247:         my %possible_part_ids; 
                   7248:         if (ref($resource->parts()) eq 'ARRAY') { 
                   7249:             foreach my $part (@{$resource->parts()}) {
1.513.2.1  raeburn  7250:                 if (!&Apache::loncommon::check_if_partid_hidden($part,$symb,$udom,$uname)) {
                   7251:                     my @resp_ids = $resource->responseIds($part);
                   7252:                     foreach my $id (@resp_ids) {
                   7253:                         $possible_part_ids{$part.'.'.$id} = 1;
                   7254:                     }
1.503     raeburn  7255:                 }
                   7256:             }
                   7257:         }
1.513     foxr     7258: 	my $result=&ssi_with_retries($resource->src(), $ssi_retries,
1.513.2.2! raeburn  7259: 					('symb' => $symb,
        !          7260: 					 'grade_target' => 'analyze',
        !          7261: 					 'grade_courseid' => $cid,
        !          7262: 					 'grade_domain' => $udom,
        !          7263: 					 'grade_username' => $uname));
1.436     albertel 7264: 	my (undef, $an) =
1.435     foxr     7265: 	    split(/_HASH_REF__/,$result, 2);
                   7266: 
1.503     raeburn  7267:         my @parts;
                   7268: 
1.435     foxr     7269: 	my %analysis = &Apache::lonnet::str2hash($an);
                   7270: 
1.503     raeburn  7271:         if (ref($analysis{'parts'}) eq 'ARRAY') {
1.513.2.1  raeburn  7272:             foreach my $part (@{$analysis{'parts'}}) {
                   7273:                 my ($id,$respid) = split(/\./,$part);
                   7274:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                   7275:                     push(@parts,$part);
                   7276:                 }
                   7277:             }
1.503     raeburn  7278:         }
                   7279:         # Add part_ids for any essayresponse items. 
                   7280:         foreach my $part_id (keys(%possible_part_ids)) {
1.510     raeburn  7281:             if (($analysis{$part_id.'.type'} eq 'essayresponse') ||
                   7282:                 ($analysis{$part_id.'.type'} eq 'reactionresponse') ||
                   7283:                 ($analysis{$part_id.'.type'} eq 'organicresponse')) {
1.503     raeburn  7284:                 if (!grep(/^\Q$part_id\E$/,@parts)) {
                   7285:                     push (@parts,$part_id);
                   7286:                 }
                   7287:             }
                   7288:         }
1.435     foxr     7289: 
1.503     raeburn  7290: 	foreach my $part_id (@parts) {
                   7291:             my $lines = $analysis{"$part_id.bubble_lines"};
1.447     foxr     7292: 
                   7293: 	    # TODO - make this a persistent hash not an array.
                   7294: 
1.509     raeburn  7295:             # optionresponse, matchresponse and rankresponse type items 
                   7296:             # render as separate sub-questions in exam mode.
1.503     raeburn  7297:             if (($analysis{$part_id.'.type'} eq 'optionresponse') ||
1.509     raeburn  7298:                 ($analysis{$part_id.'.type'} eq 'matchresponse') ||
                   7299:                 ($analysis{$part_id.'.type'} eq 'rankresponse')) {
1.503     raeburn  7300:                 my ($numbub,$numshown);
                   7301:                 if ($analysis{$part_id.'.type'} eq 'optionresponse') {
                   7302:                     if (ref($analysis{$part_id.'.options'}) eq 'ARRAY') {
                   7303:                         $numbub = scalar(@{$analysis{$part_id.'.options'}});
                   7304:                     }
                   7305:                 } elsif ($analysis{$part_id.'.type'} eq 'matchresponse') {
                   7306:                     if (ref($analysis{$part_id.'.items'}) eq 'ARRAY') {
                   7307:                         $numbub = scalar(@{$analysis{$part_id.'.items'}});
                   7308:                     }
1.509     raeburn  7309:                 } elsif ($analysis{$part_id.'.type'} eq 'rankresponse') {
                   7310:                     if (ref($analysis{$part_id.'.foils'}) eq 'ARRAY') {
                   7311:                         $numbub = scalar(@{$analysis{$part_id.'.foils'}});
                   7312:                     }
1.503     raeburn  7313:                 }
                   7314:                 if (ref($analysis{$part_id.'.shown'}) eq 'ARRAY') {
                   7315:                     $numshown = scalar(@{$analysis{$part_id.'.shown'}});
                   7316:                 }
                   7317:                 my $bubbles_per_line = 10;
                   7318:                 my $inner_bubble_lines = int($numshown/$bubbles_per_line);
                   7319:                 if (($numshown % $bubbles_per_line) != 0) {
                   7320:                     $inner_bubble_lines++;
                   7321:                 }
                   7322:                 for (my $i=0; $i<$numshown; $i++) {
                   7323:                     $subdivided_bubble_lines{$response_number} .= 
                   7324:                         $inner_bubble_lines.',';
                   7325:                 }
                   7326:                 $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7327:             } 
1.447     foxr     7328: 
1.503     raeburn  7329:             $first_bubble_line{$response_number} = $bubble_line;
                   7330: 	    $bubble_lines_per_response{$response_number} = $lines;
                   7331:             $responsetype_per_response{$response_number} = 
                   7332:                 $analysis{$part_id.'.type'};
1.447     foxr     7333: 	    $response_number++;
                   7334: 
                   7335: 	    $bubble_line +=  $lines;
                   7336: 	    $total_lines +=  $lines;
1.435     foxr     7337: 	}
                   7338: 
1.191     albertel 7339:     }
                   7340:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     7341: 
                   7342:     &save_bubble_lines();
1.330     albertel 7343:     $env{'form.scantron_maxbubble'} =
1.435     foxr     7344: 	$total_lines;
1.257     albertel 7345:     return $env{'form.scantron_maxbubble'};
1.191     albertel 7346: }
                   7347: 
1.423     albertel 7348: =pod
                   7349: 
                   7350: =item scantron_validate_missingbubbles
                   7351: 
1.424     albertel 7352:    Validates all scanlines in the selected file to not have any
1.447     foxr     7353:     answers that don't have bubbles that have not been verified
                   7354:     to be bubble free.
1.424     albertel 7355: 
1.423     albertel 7356: =cut
                   7357: 
1.157     albertel 7358: sub scantron_validate_missingbubbles {
                   7359:     my ($r,$currentphase) = @_;
                   7360:     #get student info
                   7361:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7362:     my %idmap=&username_to_idmap($classlist);
                   7363: 
                   7364:     #get scantron line setup
1.257     albertel 7365:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7366:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7367:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7368:     if (!$max_bubble) { $max_bubble=2**31; }
                   7369:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7370: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7371: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7372: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7373: 						 $scan_data);
                   7374: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7375: 	my @to_correct;
1.470     foxr     7376: 	
                   7377: 	# Probably here's where the error is...
                   7378: 
1.157     albertel 7379: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7380:             my $lastbubble;
                   7381:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7382:                my $question = $1;
                   7383:                my $subquestion = $2;
                   7384:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7385:                my $first = $first_bubble_line{$question-1};
                   7386:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7387:                my $subcount = 1;
                   7388:                while ($subcount<$subquestion) {
                   7389:                    $first += $subans[$subcount-1];
                   7390:                    $subcount ++;
                   7391:                }
                   7392:                my $count = $subans[$subquestion-1];
                   7393:                $lastbubble = $first + $count;
                   7394:             } else {
                   7395:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7396:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7397:             }
                   7398:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7399: 	    push(@to_correct,$missing);
                   7400: 	}
                   7401: 	if (@to_correct) {
                   7402: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7403: 				     $line,'missingbubble',\@to_correct);
                   7404: 	    return (1,$currentphase);
                   7405: 	}
                   7406: 
                   7407:     }
                   7408:     return (0,$currentphase+1);
                   7409: }
                   7410: 
1.423     albertel 7411: =pod
                   7412: 
                   7413: =item scantron_process_students
                   7414: 
                   7415:    Routine that does the actual grading of the bubble sheet information.
                   7416: 
                   7417:    The parsed scanline hash is added to %env 
                   7418: 
                   7419:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   7420:    foreach resource , with the form data of
                   7421: 
                   7422: 	'submitted'     =>'scantron' 
                   7423: 	'grade_target'  =>'grade',
                   7424: 	'grade_username'=> username of student
                   7425: 	'grade_domain'  => domain of student
                   7426: 	'grade_courseid'=> of course
                   7427: 	'grade_symb'    => symb of resource to grade
                   7428: 
                   7429:     This triggers a grading pass. The problem grading code takes care
                   7430:     of converting the bubbled letter information (now in %env) into a
                   7431:     valid submission.
                   7432: 
                   7433: =cut
                   7434: 
1.82      albertel 7435: sub scantron_process_students {
1.75      albertel 7436:     my ($r) = @_;
1.513     foxr     7437: 
1.257     albertel 7438:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7439:     my ($symb)=&get_symb($r);
1.513     foxr     7440:     if (!$symb) {
                   7441: 	return '';
                   7442:     }
1.324     albertel 7443:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7444: 
1.257     albertel 7445:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7446:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7447:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7448:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7449:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7450:     my $map=$navmap->getResourceByUrl($sequence);
                   7451:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 7452: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 7453:     my $result= <<SCANTRONFORM;
1.81      albertel 7454: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7455:   <input type="hidden" name="command" value="scantron_configphase" />
                   7456:   $default_form_data
                   7457: SCANTRONFORM
1.82      albertel 7458:     $r->print($result);
                   7459: 
                   7460:     my @delayqueue;
1.140     albertel 7461:     my %completedstudents;
                   7462:     
1.200     albertel 7463:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7464:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7465:  				    'Scantron Progress',$count,
1.195     albertel 7466: 				    'inline',undef,'scantronupload');
1.140     albertel 7467:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7468: 					  'Processing first student');
                   7469:     my $start=&Time::HiRes::time();
1.158     albertel 7470:     my $i=-1;
1.200     albertel 7471:     my ($uname,$udom,$started);
1.447     foxr     7472: 
                   7473:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
1.513     foxr     7474:     
                   7475: 
                   7476:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7477:     # the user and return.
                   7478: 
                   7479:     if ($ssi_error) {
                   7480: 	$r->print("</form>");
                   7481: 	&ssi_print_error($r);
                   7482: 	$r->print(&show_grading_menu_form($symb));
                   7483: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7484:     }
1.447     foxr     7485: 
1.157     albertel 7486:     while ($i<$scanlines->{'count'}) {
                   7487:  	($uname,$udom)=('','');
                   7488:  	$i++;
1.200     albertel 7489:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7490:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7491: 	if ($started) {
                   7492: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7493: 						     'last student');
                   7494: 	}
                   7495: 	$started=1;
1.157     albertel 7496:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7497:  						 $scan_data);
                   7498:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7499:  					      \%idmap,$i)) {
                   7500:   	    &scantron_add_delay(\@delayqueue,$line,
                   7501:  				'Unable to find a student that matches',1);
                   7502:  	    next;
                   7503:   	}
                   7504:  	if (exists $completedstudents{$uname}) {
                   7505:  	    &scantron_add_delay(\@delayqueue,$line,
                   7506:  				'Student '.$uname.' has multiple sheets',2);
                   7507:  	    next;
                   7508:  	}
                   7509:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7510: 
                   7511: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 7512:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 7513: 
                   7514: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7515: 	    &scantron_putfile($scanlines,$scan_data);
                   7516: 	}
1.161     albertel 7517: 	
                   7518: 	my $i=0;
1.83      albertel 7519: 	foreach my $resource (@resources) {
1.85      albertel 7520: 	    $i++;
1.193     albertel 7521: 	    my %form=('submitted'     =>'scantron',
                   7522: 		      'grade_target'  =>'grade',
                   7523: 		      'grade_username'=>$uname,
                   7524: 		      'grade_domain'  =>$udom,
1.257     albertel 7525: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 7526: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 7527: 	    if (exists($scan_record->{'scantron.CODE'})
                   7528: 		&& 
                   7529: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 7530: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 7531: 	    } else {
                   7532: 		$form{'CODE'}='';
1.513     foxr     7533: 	    } 
                   7534: 	    my $result=&ssi_with_retries($resource->src(), $ssi_retries, %form);
                   7535: 	    if ($ssi_error) {
                   7536: 		$ssi_error = 0;	# So end of handler error message does not trigger.
                   7537: 		$r->print("</form>");
                   7538: 		&ssi_print_error($r);
                   7539: 		$r->print(&show_grading_menu_form($symb));
                   7540: 		return '';	# Why return ''?  Beats me.
1.193     albertel 7541: 	    }
1.513     foxr     7542: 
1.213     albertel 7543: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7544: 	}
1.140     albertel 7545: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7546: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7547:     } continue {
1.330     albertel 7548: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7549: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7550:     }
1.140     albertel 7551:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 7552: #    my $lasttime = &Time::HiRes::time()-$start;
                   7553: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7554: 
1.200     albertel 7555:     $r->print("</form>");
1.324     albertel 7556:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7557:     return '';
1.75      albertel 7558: }
1.157     albertel 7559: 
1.423     albertel 7560: =pod
                   7561: 
                   7562: =item scantron_upload_scantron_data
                   7563: 
                   7564:     Creates the screen for adding a new bubble sheet data file to a course.
                   7565: 
                   7566: =cut
                   7567: 
1.157     albertel 7568: sub scantron_upload_scantron_data {
                   7569:     my ($r)=@_;
1.257     albertel 7570:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7571:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7572: 							  'domainid',
                   7573: 							  'coursename');
1.257     albertel 7574:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7575: 						   'domainid');
1.324     albertel 7576:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7577:     $r->print('
1.157     albertel 7578: <script type="text/javascript" language="javascript">
                   7579:     function checkUpload(formname) {
                   7580: 	if (formname.upfile.value == "") {
                   7581: 	    alert("Please use the browse button to select a file from your local directory.");
                   7582: 	    return false;
                   7583: 	}
                   7584: 	formname.submit();
                   7585:     }
                   7586: </script>
                   7587: 
1.492     albertel 7588: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7589: '.$default_form_data.'
1.181     albertel 7590: <table>
1.492     albertel 7591: <tr><td>'.$select_link.'                             </td></tr>
                   7592: <tr><td>'.&mt('Course ID:').'     </td>
                   7593:     <td><input name="courseid"   type="text" />      </td></tr>
                   7594: <tr><td>'.&mt('Course Name:').'   </td>
                   7595:     <td><input name="coursename" type="text" />      </td></tr>
                   7596: <tr><td>'.&mt('Domain:').'        </td>
                   7597:     <td>'.$domsel.'                                  </td></tr>
                   7598: <tr><td>'.&mt('File to upload:').'</td>
                   7599:     <td><input type="file" name="upfile" size="50" /></td></tr>
1.181     albertel 7600: </table>
1.492     albertel 7601: <input name="command" value="scantronupload_save" type="hidden" />
                   7602: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.157     albertel 7603: </form>
1.492     albertel 7604: ');
1.157     albertel 7605:     return '';
                   7606: }
                   7607: 
1.423     albertel 7608: =pod
                   7609: 
                   7610: =item scantron_upload_scantron_data_save
                   7611: 
                   7612:    Adds a provided bubble information data file to the course if user
                   7613:    has the correct privileges to do so.  
                   7614: 
                   7615: =cut
                   7616: 
1.157     albertel 7617: sub scantron_upload_scantron_data_save {
                   7618:     my($r)=@_;
1.324     albertel 7619:     my ($symb)=&get_symb($r,1);
1.182     albertel 7620:     my $doanotherupload=
                   7621: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7622: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7623: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7624: 	'</form>'."\n";
1.257     albertel 7625:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7626: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7627: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.492     albertel 7628: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
1.182     albertel 7629: 	if ($symb) {
1.324     albertel 7630: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7631: 	} else {
                   7632: 	    $r->print($doanotherupload);
                   7633: 	}
1.162     albertel 7634: 	return '';
                   7635:     }
1.257     albertel 7636:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.492     albertel 7637:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
1.257     albertel 7638:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7639:     #FIXME
                   7640:     #copied from lonnet::userfileupload()
                   7641:     #make that function able to target a specified course
                   7642:     # Replace Windows backslashes by forward slashes
                   7643:     $fname=~s/\\/\//g;
                   7644:     # Get rid of everything but the actual filename
                   7645:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7646:     # Replace spaces by underscores
                   7647:     $fname=~s/\s+/\_/g;
                   7648:     # Replace all other weird characters by nothing
                   7649:     $fname=~s/[^\w\.\-]//g;
                   7650:     # See if there is anything left
                   7651:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7652:     my $uploadedfile=$fname;
1.157     albertel 7653:     $fname='scantron_orig_'.$fname;
1.257     albertel 7654:     if (length($env{'form.upfile'}) < 2) {
1.492     albertel 7655: 	$r->print(&mt("<span class=\"LC_error\">Error:</span> The file you attempted to upload, [_1]  contained no information. Please check that you entered the correct filename.",'<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
1.183     albertel 7656:     } else {
1.275     albertel 7657: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7658: 	if ($result =~ m|^/uploaded/|) {
1.492     albertel 7659: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
                   7660: 			  (length($env{'form.upfile'})-1),
                   7661: 			  '<span class="LC_filename">'.$result."</span>"));
1.210     albertel 7662: 	} else {
1.492     albertel 7663: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
                   7664: 			  $result,
                   7665: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
                   7666: 
1.183     albertel 7667: 	}
                   7668:     }
1.174     albertel 7669:     if ($symb) {
1.209     ng       7670: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7671:     } else {
1.182     albertel 7672: 	$r->print($doanotherupload);
1.174     albertel 7673:     }
1.157     albertel 7674:     return '';
                   7675: }
                   7676: 
1.423     albertel 7677: =pod
                   7678: 
                   7679: =item valid_file
                   7680: 
1.424     albertel 7681:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7682: 
                   7683: =cut
                   7684: 
1.202     albertel 7685: sub valid_file {
                   7686:     my ($requested_file)=@_;
                   7687:     foreach my $filename (sort(&scantron_filenames())) {
                   7688: 	if ($requested_file eq $filename) { return 1; }
                   7689:     }
                   7690:     return 0;
                   7691: }
                   7692: 
1.423     albertel 7693: =pod
                   7694: 
                   7695: =item scantron_download_scantron_data
                   7696: 
                   7697:    Shows a list of the three internal files (original, corrected,
                   7698:    skipped) for a specific bubble sheet data file that exists in the
                   7699:    course.
                   7700: 
                   7701: =cut
                   7702: 
1.202     albertel 7703: sub scantron_download_scantron_data {
                   7704:     my ($r)=@_;
1.324     albertel 7705:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7706:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7707:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7708:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7709:     if (! &valid_file($file)) {
1.492     albertel 7710: 	$r->print('
1.202     albertel 7711: 	<p>
1.492     albertel 7712: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7713:         </p>
1.492     albertel 7714: ');
1.324     albertel 7715: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7716: 	return;
                   7717:     }
                   7718:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7719:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7720:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7721:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7722:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7723:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7724:     $r->print('
1.202     albertel 7725:     <p>
1.492     albertel 7726: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7727: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7728:     </p>
                   7729:     <p>
1.492     albertel 7730: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7731: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7732:     </p>
                   7733:     <p>
1.492     albertel 7734: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7735: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7736:     </p>
1.492     albertel 7737: ');
1.324     albertel 7738:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7739:     return '';
                   7740: }
1.157     albertel 7741: 
1.423     albertel 7742: =pod
                   7743: 
                   7744: =back
                   7745: 
                   7746: =cut
                   7747: 
1.75      albertel 7748: #-------- end of section for handling grading scantron forms -------
                   7749: #
                   7750: #-------------------------------------------------------------------
                   7751: 
1.72      ng       7752: #-------------------------- Menu interface -------------------------
                   7753: #
                   7754: #--- Show a Grading Menu button - Calls the next routine ---
                   7755: sub show_grading_menu_form {
1.324     albertel 7756:     my ($symb)=@_;
1.125     ng       7757:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7758: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7759: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7760: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 7761: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       7762: 	'</form>'."\n";
                   7763:     return $result;
                   7764: }
                   7765: 
1.77      ng       7766: # -- Retrieve choices for grading form
                   7767: sub savedState {
                   7768:     my %savedState = ();
1.257     albertel 7769:     if ($env{'form.saveState'}) {
                   7770: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7771: 	    my ($key,$value) = split(/=/,$_,2);
                   7772: 	    $savedState{$key} = $value;
                   7773: 	}
                   7774:     }
                   7775:     return \%savedState;
                   7776: }
1.76      ng       7777: 
1.443     banghart 7778: sub grading_menu {
                   7779:     my ($request) = @_;
                   7780:     my ($symb)=&get_symb($request);
                   7781:     if (!$symb) {return '';}
                   7782:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7783:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7784: 
1.444     banghart 7785:     $request->print($table);
1.443     banghart 7786:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7787:                   'handgrade'=>$hdgrade,
                   7788:                   'probTitle'=>$probTitle,
                   7789:                   'command'=>'submit_options',
                   7790:                   'saveState'=>"",
                   7791:                   'gradingMenu'=>1,
                   7792:                   'showgrading'=>"yes");
                   7793:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7794:     my @menu = ({ url => $url,
                   7795:                      name => &mt('Manual Grading/View Submissions'),
                   7796:                      short_description => 
                   7797:     &mt('Start the process of hand grading submissions.'),
                   7798:                  });
                   7799:     $fields{'command'} = 'csvform';
                   7800:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7801:     push (@menu, { url => $url,
                   7802:                    name => &mt('Upload Scores'),
                   7803:                    short_description => 
                   7804:             &mt('Specify a file containing the class scores for current resource.')});
                   7805:     $fields{'command'} = 'processclicker';
                   7806:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7807:     push (@menu, { url => $url,
                   7808:                    name => &mt('Process Clicker'),
                   7809:                    short_description => 
                   7810:             &mt('Specify a file containing the clicker information for this resource.')});
                   7811:     $fields{'command'} = 'scantron_selectphase';
                   7812:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7813:     push (@menu, { url => $url,
1.454     banghart 7814:                    name => &mt('Grade/Manage Scantron Forms'),
                   7815:                    short_description => 
                   7816:             &mt('')});
1.443     banghart 7817:     $fields{'command'} = 'verify';
                   7818:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7819:     push (@menu, { url => "",
1.443     banghart 7820:                    name => &mt('Verify Receipt'),
                   7821:                    short_description => 
                   7822:             &mt('')});
                   7823:     #
                   7824:     # Create the menu
                   7825:     my $Str;
1.444     banghart 7826:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7827:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7828:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7829:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7830: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 7831: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 7832: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7833: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7834: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7835: 
1.443     banghart 7836:     foreach my $menudata (@menu) {
1.445     banghart 7837:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7838:             $Str .='    <h3><a '.
                   7839:                 $menudata->{'jscript'}.
                   7840:                 ' href="'.
                   7841:                 $menudata->{'url'}.'" >'.
                   7842:                 $menudata->{'name'}."</a></h3>\n";
                   7843:         } else {
1.511     www      7844:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
1.445     banghart 7845:                 $menudata->{'jscript'}.
1.458     banghart 7846:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.511     www      7847:                 ' /> '.
                   7848: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
                   7849:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 7850:         }
1.443     banghart 7851:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7852:             "\n";
                   7853:     }
1.444     banghart 7854:     $Str .="</form>\n";
1.443     banghart 7855:     $request->print(<<GRADINGMENUJS);
                   7856: <script type="text/javascript" language="javascript">
                   7857:     function checkChoice(formname,val,cmdx) {
                   7858: 	if (val <= 2) {
                   7859: 	    var cmd = radioSelection(formname.radioChoice);
                   7860: 	    var cmdsave = cmd;
                   7861: 	} else {
                   7862: 	    cmd = cmdx;
                   7863: 	    cmdsave = 'submission';
                   7864: 	}
                   7865: 	formname.command.value = cmd;
                   7866: 	if (val < 5) formname.submit();
                   7867: 	if (val == 5) {
1.458     banghart 7868: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   7869: 	        return false;
                   7870: 	    } else {
                   7871: 	        formname.submit();
                   7872: 	    }
1.445     banghart 7873: 	}
                   7874:     }
1.443     banghart 7875: 
                   7876:     function checkReceiptNo(formname,nospace) {
                   7877: 	var receiptNo = formname.receipt.value;
                   7878: 	var checkOpt = false;
                   7879: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7880: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7881: 	if (checkOpt) {
                   7882: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7883: 	    formname.receipt.value = "";
                   7884: 	    formname.receipt.focus();
                   7885: 	    return false;
                   7886: 	}
                   7887: 	return true;
                   7888:     }
                   7889: </script>
                   7890: GRADINGMENUJS
                   7891:     &commonJSfunctions($request);
                   7892:     return $Str;    
                   7893: }
                   7894: 
                   7895: 
                   7896: #--- Displays the submissions first page -------
                   7897: sub submit_options {
1.72      ng       7898:     my ($request) = @_;
1.324     albertel 7899:     my ($symb)=&get_symb($request);
1.72      ng       7900:     if (!$symb) {return '';}
1.76      ng       7901:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7902: 
                   7903:     $request->print(<<GRADINGMENUJS);
                   7904: <script type="text/javascript" language="javascript">
1.116     ng       7905:     function checkChoice(formname,val,cmdx) {
                   7906: 	if (val <= 2) {
                   7907: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7908: 	    var cmdsave = cmd;
1.116     ng       7909: 	} else {
                   7910: 	    cmd = cmdx;
1.118     ng       7911: 	    cmdsave = 'submission';
1.116     ng       7912: 	}
                   7913: 	formname.command.value = cmd;
1.118     ng       7914: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7915: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7916: 	if (val < 5) formname.submit();
                   7917: 	if (val == 5) {
1.72      ng       7918: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7919: 	    formname.submit();
                   7920: 	}
1.238     albertel 7921: 	if (val < 7) formname.submit();
1.72      ng       7922:     }
                   7923: 
                   7924:     function checkReceiptNo(formname,nospace) {
                   7925: 	var receiptNo = formname.receipt.value;
                   7926: 	var checkOpt = false;
                   7927: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7928: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7929: 	if (checkOpt) {
                   7930: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7931: 	    formname.receipt.value = "";
                   7932: 	    formname.receipt.focus();
                   7933: 	    return false;
                   7934: 	}
                   7935: 	return true;
                   7936:     }
                   7937: </script>
                   7938: GRADINGMENUJS
1.118     ng       7939:     &commonJSfunctions($request);
1.324     albertel 7940:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 7941:     my $result;
1.76      ng       7942:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7943:     my $savedState = &savedState();
1.118     ng       7944:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7945:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7946:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7947:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7948: 
                   7949:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7950: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7951: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7952: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7953: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7954: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7955: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7956: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7957: 
1.472     albertel 7958:     $result.='
                   7959:     <div class="LC_grade_select_mode">
1.473     albertel 7960:       <div class="LC_grade_select_mode_current">
                   7961:         <h2>
                   7962:           '.&mt('Grade Current Resource').'
                   7963:         </h2>
                   7964:         <div class="LC_grade_select_mode_body">
                   7965:           <div class="LC_grades_resource_info">
                   7966:            '.$table.'
                   7967:           </div>
                   7968:           <div class="LC_grade_select_mode_selector">
                   7969:              <div class="LC_grade_select_mode_selector_header">
                   7970:                 '.&mt('Sections').'
                   7971:              </div>
                   7972:              <div class="LC_grade_select_mode_selector_body">
                   7973: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       7974:     if (ref($sections)) {
1.472     albertel 7975: 	foreach my $section (sort (@$sections)) {
                   7976: 	    $result.='<option value="'.$section.'" '.
                   7977: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 7978: 	}
1.116     ng       7979:     }
1.401     albertel 7980:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 7981:     $result.='
1.473     albertel 7982:              </div>
                   7983:           </div>
                   7984:           <div class="LC_grade_select_mode_selector">
                   7985:              <div class="LC_grade_select_mode_selector_header">
                   7986:                 '.&mt('Groups').'
                   7987:              </div>
                   7988:              <div class="LC_grade_select_mode_selector_body">
                   7989:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   7990:              </div>
1.472     albertel 7991:           </div>
1.473     albertel 7992:           <div class="LC_grade_select_mode_selector">
                   7993:              <div class="LC_grade_select_mode_selector_header">
                   7994:                 '.&mt('Access Status').'
                   7995:              </div>
                   7996:              <div class="LC_grade_select_mode_selector_body">
                   7997:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   7998:              </div>
1.472     albertel 7999:           </div>
1.473     albertel 8000:           <div class="LC_grade_select_mode_selector">
                   8001:              <div class="LC_grade_select_mode_selector_header">
                   8002:                 '.&mt('Submission Status').'
                   8003:              </div>
                   8004:              <div class="LC_grade_select_mode_selector_body">
                   8005:                <select name="submitonly" size="5">
                   8006: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8007: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8008: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8009: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8010:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   8011:                </select>
                   8012:              </div>
1.472     albertel 8013:           </div>
1.473     albertel 8014:           <div class="LC_grade_select_mode_type_body">
                   8015:             <div class="LC_grade_select_mode_type">
                   8016:               <label>
                   8017:                 <input type="radio" name="radioChoice" value="submission" '.
                   8018:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8019:              &mt('Select individual students to grade and view submissions.').'
                   8020: 	      </label> 
                   8021:             </div>
                   8022:             <div class="LC_grade_select_mode_type">
                   8023: 	      <label>
                   8024:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8025:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8026:                     &mt('Grade all selected students in a grading table.').'
                   8027:               </label>
                   8028:             </div>
                   8029:             <div class="LC_grade_select_mode_type">
                   8030: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   8031:             </div>
1.472     albertel 8032:           </div>
1.473     albertel 8033:         </div>
                   8034:       </div>
                   8035:       <div class="LC_grade_select_mode_page">
                   8036:         <h2>
                   8037:          '.&mt('Grade Complete Folder for One Student').'
                   8038:         </h2>
                   8039:         <div class="LC_grades_select_mode_body">
                   8040:           <div class="LC_grade_select_mode_type_body">
                   8041:             <div class="LC_grade_select_mode_type">
                   8042:               <label>
                   8043:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8044: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8045:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8046:               </label>
                   8047:             </div>
                   8048:             <div class="LC_grade_select_mode_type">
                   8049: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   8050:             </div>
1.472     albertel 8051:           </div>
                   8052:         </div>
                   8053:       </div>
                   8054:     </div>
                   8055:   </form>';
1.499     albertel 8056:     $result .= &show_grading_menu_form($symb);
1.44      ng       8057:     return $result;
1.2       albertel 8058: }
                   8059: 
1.285     albertel 8060: sub reset_perm {
                   8061:     undef(%perm);
                   8062: }
                   8063: 
                   8064: sub init_perm {
                   8065:     &reset_perm();
1.300     albertel 8066:     foreach my $test_perm ('vgr','mgr','opa') {
                   8067: 
                   8068: 	my $scope = $env{'request.course.id'};
                   8069: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8070: 
                   8071: 	    $scope .= '/'.$env{'request.course.sec'};
                   8072: 	    if ( $perm{$test_perm}=
                   8073: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8074: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8075: 	    } else {
                   8076: 		delete($perm{$test_perm});
                   8077: 	    }
1.285     albertel 8078: 	}
                   8079:     }
                   8080: }
                   8081: 
1.400     www      8082: sub gather_clicker_ids {
1.408     albertel 8083:     my %clicker_ids;
1.400     www      8084: 
                   8085:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8086: 
                   8087:     # Set up a couple variables.
1.407     albertel 8088:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8089:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8090:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8091: 
1.407     albertel 8092:     foreach my $student (keys(%$classlist)) {
1.438     www      8093:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8094:         my $username = $classlist->{$student}->[$username_idx];
                   8095:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8096:         my $clickers =
1.408     albertel 8097: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8098:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8099:             $id=~s/^[\#0]+//;
1.421     www      8100:             $id=~s/[\-\:]//g;
1.407     albertel 8101:             if (exists($clicker_ids{$id})) {
1.408     albertel 8102: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8103:             } else {
1.408     albertel 8104: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8105:             }
                   8106:         }
                   8107:     }
1.407     albertel 8108:     return %clicker_ids;
1.400     www      8109: }
                   8110: 
1.402     www      8111: sub gather_adv_clicker_ids {
1.408     albertel 8112:     my %clicker_ids;
1.402     www      8113:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8114:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8115:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8116:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8117:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8118:             my ($puname,$pudom)=split(/\:/,$person);
                   8119:             my $clickers =
1.408     albertel 8120: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8121:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8122: 		$id=~s/^[\#0]+//;
1.421     www      8123:                 $id=~s/[\-\:]//g;
1.408     albertel 8124: 		if (exists($clicker_ids{$id})) {
                   8125: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8126: 		} else {
                   8127: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8128: 		}
1.405     www      8129:             }
1.402     www      8130:         }
                   8131:     }
1.407     albertel 8132:     return %clicker_ids;
1.402     www      8133: }
                   8134: 
1.413     www      8135: sub clicker_grading_parameters {
                   8136:     return ('gradingmechanism' => 'scalar',
                   8137:             'upfiletype' => 'scalar',
                   8138:             'specificid' => 'scalar',
                   8139:             'pcorrect' => 'scalar',
                   8140:             'pincorrect' => 'scalar');
                   8141: }
                   8142: 
1.400     www      8143: sub process_clicker {
                   8144:     my ($r)=@_;
                   8145:     my ($symb)=&get_symb($r);
                   8146:     if (!$symb) {return '';}
                   8147:     my $result=&checkforfile_js();
                   8148:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8149:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8150:     $result.=$table;
                   8151:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8152:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   8153:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   8154:         '.</b></td></tr>'."\n";
                   8155:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8156: # Attempt to restore parameters from last session, set defaults if not present
                   8157:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8158:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8159:                                                  \%Saveable_Parameters);
                   8160:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8161:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8162:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8163:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8164: 
                   8165:     my %checked;
                   8166:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   8167:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   8168:           $checked{$gradingmechanism}="checked='checked'";
                   8169:        }
                   8170:     }
                   8171: 
1.400     www      8172:     my $upload=&mt("Upload File");
                   8173:     my $type=&mt("Type");
1.402     www      8174:     my $attendance=&mt("Award points just for participation");
                   8175:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8176:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      8177:     my $pcorrect=&mt("Percentage points for correct solution");
                   8178:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8179:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8180: 						   ('iclicker' => 'i>clicker',
                   8181:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8182:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8183:     $result.=<<ENDUPFORM;
1.402     www      8184: <script type="text/javascript">
                   8185: function sanitycheck() {
                   8186: // Accept only integer percentages
                   8187:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8188:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8189: // Find out grading choice
                   8190:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8191:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8192:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8193:       }
                   8194:    }
                   8195: // By default, new choice equals user selection
                   8196:    newgradingchoice=gradingchoice;
                   8197: // Not good to give more points for false answers than correct ones
                   8198:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8199:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8200:    }
                   8201: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8202:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8203:       document.forms.gradesupload.pcorrect.value=100;
                   8204:       document.forms.gradesupload.pincorrect.value=100;
                   8205:    }
                   8206: // If the values are different, cannot be attendance only
                   8207:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8208:        (gradingchoice=='attendance')) {
                   8209:        newgradingchoice='personnel';
                   8210:    }
                   8211: // Change grading choice to new one
                   8212:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8213:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8214:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8215:       } else {
                   8216:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8217:       }
                   8218:    }
                   8219: // Remember the old state
                   8220:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8221: }
                   8222: </script>
1.400     www      8223: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8224: <input type="hidden" name="symb" value="$symb" />
                   8225: <input type="hidden" name="command" value="processclickerfile" />
                   8226: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8227: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8228: <input type="file" name="upfile" size="50" />
                   8229: <br /><label>$type: $selectform</label>
1.451     albertel 8230: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8231: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8232: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8233: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      8234: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8235: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8236: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8237: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8238: </form>
                   8239: ENDUPFORM
                   8240:     $result.='</td></tr></table>'."\n".
                   8241:              '</td></tr></table><br /><br />'."\n";
                   8242:     $result.=&show_grading_menu_form($symb);
                   8243:     return $result;
                   8244: }
                   8245: 
                   8246: sub process_clicker_file {
                   8247:     my ($r)=@_;
                   8248:     my ($symb)=&get_symb($r);
                   8249:     if (!$symb) {return '';}
1.413     www      8250: 
                   8251:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8252:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8253:                                               \%Saveable_Parameters);
                   8254: 
1.400     www      8255:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8256:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8257: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8258: 	return $result.&show_grading_menu_form($symb);
1.404     www      8259:     }
1.407     albertel 8260:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8261:     my %correct_ids;
1.404     www      8262:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8263: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8264:     }
                   8265:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8266: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8267: 	   $correct_id=~tr/a-z/A-Z/;
                   8268: 	   $correct_id=~s/\s//gs;
                   8269: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8270:            $correct_id=~s/[\-\:]//g;
1.414     www      8271:            if ($correct_id) {
                   8272: 	      $correct_ids{$correct_id}='specified';
                   8273:            }
                   8274:         }
1.400     www      8275:     }
1.404     www      8276:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8277: 	$result.=&mt('Score based on attendance only');
1.404     www      8278:     } else {
1.408     albertel 8279: 	my $number=0;
1.411     www      8280: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8281: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8282: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8283: 	    if ($correct_ids{$id} eq 'specified') {
                   8284: 		$result.=&mt('specified');
                   8285: 	    } else {
                   8286: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8287: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8288: 	    }
                   8289: 	    $number++;
                   8290: 	}
1.411     www      8291:         $result.="</p>\n";
1.408     albertel 8292: 	if ($number==0) {
                   8293: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8294: 	    return $result.&show_grading_menu_form($symb);
                   8295: 	}
1.404     www      8296:     }
1.405     www      8297:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8298:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8299: 		     '<span class="LC_error">',
                   8300: 		     '</span>',
                   8301: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8302:         return $result.&show_grading_menu_form($symb);
                   8303:     }
1.410     www      8304: 
                   8305: # Were able to get all the info needed, now analyze the file
                   8306: 
1.411     www      8307:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8308:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8309:     my $heading=&mt('Scanning clicker file');
                   8310:     $result.=(<<ENDHEADER);
                   8311: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8312: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8313: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8314: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8315: <input type="hidden" name="symb" value="$symb" />
                   8316: <input type="hidden" name="command" value="assignclickergrades" />
                   8317: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8318: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8319: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8320: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8321: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8322: ENDHEADER
1.408     albertel 8323:     my %responses;
                   8324:     my @questiontitles;
1.405     www      8325:     my $errormsg='';
                   8326:     my $number=0;
                   8327:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8328: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8329:     }
1.419     www      8330:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8331:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8332:     }
1.411     www      8333:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8334:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8335:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8336:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8337:              '<br />';
1.414     www      8338: # Remember Question Titles
                   8339: # FIXME: Possibly need delimiter other than ":"
                   8340:     for (my $i=0;$i<$number;$i++) {
                   8341:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8342:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8343:     }
1.411     www      8344:     my $correct_count=0;
                   8345:     my $student_count=0;
                   8346:     my $unknown_count=0;
1.414     www      8347: # Match answers with usernames
                   8348: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8349:     foreach my $id (keys(%responses)) {
1.410     www      8350:        if ($correct_ids{$id}) {
1.414     www      8351:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8352:           $correct_count++;
1.410     www      8353:        } elsif ($clicker_ids{$id}) {
1.437     www      8354:           if ($clicker_ids{$id}=~/\,/) {
                   8355: # More than one user with the same clicker!
                   8356:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8357:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8358:                            "<select name='multi".$id."'>";
                   8359:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8360:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8361:              }
                   8362:              $result.='</select>';
                   8363:              $unknown_count++;
                   8364:           } else {
                   8365: # Good: found one and only one user with the right clicker
                   8366:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8367:              $student_count++;
                   8368:           }
1.410     www      8369:        } else {
1.411     www      8370:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8371:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8372:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8373:                    "\n".&mt("Domain").": ".
                   8374:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8375:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8376:           $unknown_count++;
1.410     www      8377:        }
1.405     www      8378:     }
1.412     www      8379:     $result.='<hr />'.
                   8380:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   8381:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   8382:        if ($correct_count==0) {
                   8383:           $errormsg.="Found no correct answers answers for grading!";
                   8384:        } elsif ($correct_count>1) {
1.414     www      8385:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8386:        }
                   8387:     }
1.428     www      8388:     if ($number<1) {
                   8389:        $errormsg.="Found no questions.";
                   8390:     }
1.412     www      8391:     if ($errormsg) {
                   8392:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8393:     } else {
                   8394:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8395:     }
                   8396:     $result.='</form></td></tr></table>'."\n".
1.410     www      8397:              '</td></tr></table><br /><br />'."\n";
1.404     www      8398:     return $result.&show_grading_menu_form($symb);
1.400     www      8399: }
                   8400: 
1.405     www      8401: sub iclicker_eval {
1.406     www      8402:     my ($questiontitles,$responses)=@_;
1.405     www      8403:     my $number=0;
                   8404:     my $errormsg='';
                   8405:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8406:         my %components=&Apache::loncommon::record_sep($line);
                   8407:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8408: 	if ($entries[0] eq 'Question') {
                   8409: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8410: 		$$questiontitles[$number]=$entries[$i];
                   8411: 		$number++;
                   8412: 	    }
                   8413: 	}
                   8414: 	if ($entries[0]=~/^\#/) {
                   8415: 	    my $id=$entries[0];
                   8416: 	    my @idresponses;
                   8417: 	    $id=~s/^[\#0]+//;
                   8418: 	    for (my $i=0;$i<$number;$i++) {
                   8419: 		my $idx=3+$i*6;
                   8420: 		push(@idresponses,$entries[$idx]);
                   8421: 	    }
                   8422: 	    $$responses{$id}=join(',',@idresponses);
                   8423: 	}
1.405     www      8424:     }
                   8425:     return ($errormsg,$number);
                   8426: }
                   8427: 
1.419     www      8428: sub interwrite_eval {
                   8429:     my ($questiontitles,$responses)=@_;
                   8430:     my $number=0;
                   8431:     my $errormsg='';
1.420     www      8432:     my $skipline=1;
                   8433:     my $questionnumber=0;
                   8434:     my %idresponses=();
1.419     www      8435:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8436:         my %components=&Apache::loncommon::record_sep($line);
                   8437:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8438:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8439:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8440:         next if $skipline;
                   8441:         if ($entries[0]!=$questionnumber) {
                   8442:            $questionnumber=$entries[0];
                   8443:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8444:            $number++;
1.419     www      8445:         }
1.420     www      8446:         my $id=$entries[4];
                   8447:         $id=~s/^[\#0]+//;
1.421     www      8448:         $id=~s/^v\d*\://i;
                   8449:         $id=~s/[\-\:]//g;
1.420     www      8450:         $idresponses{$id}[$number]=$entries[6];
                   8451:     }
                   8452:     foreach my $id (keys %idresponses) {
                   8453:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8454:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8455:     }
                   8456:     return ($errormsg,$number);
                   8457: }
                   8458: 
1.414     www      8459: sub assign_clicker_grades {
                   8460:     my ($r)=@_;
                   8461:     my ($symb)=&get_symb($r);
                   8462:     if (!$symb) {return '';}
1.416     www      8463: # See which part we are saving to
                   8464:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8465: # FIXME: This should probably look for the first handgradeable part
                   8466:     my $part=$$partlist[0];
                   8467: # Start screen output
1.414     www      8468:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8469: 
1.414     www      8470:     my $heading=&mt('Assigning grades based on clicker file');
                   8471:     $result.=(<<ENDHEADER);
                   8472: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8473: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8474: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8475: ENDHEADER
                   8476: # Get correct result
                   8477: # FIXME: Possibly need delimiter other than ":"
                   8478:     my @correct=();
1.415     www      8479:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8480:     my $number=$env{'form.number'};
                   8481:     if ($gradingmechanism ne 'attendance') {
1.414     www      8482:        foreach my $key (keys(%env)) {
                   8483:           if ($key=~/^form\.correct\:/) {
                   8484:              my @input=split(/\,/,$env{$key});
                   8485:              for (my $i=0;$i<=$#input;$i++) {
                   8486:                  if (($correct[$i]) && ($input[$i]) &&
                   8487:                      ($correct[$i] ne $input[$i])) {
                   8488:                     $result.='<br /><span class="LC_warning">'.
                   8489:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8490:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8491:                  } elsif ($input[$i]) {
                   8492:                     $correct[$i]=$input[$i];
                   8493:                  }
                   8494:              }
                   8495:           }
                   8496:        }
1.415     www      8497:        for (my $i=0;$i<$number;$i++) {
1.414     www      8498:           if (!$correct[$i]) {
                   8499:              $result.='<br /><span class="LC_error">'.
                   8500:                       &mt('No correct result given for question "[_1]"!',
                   8501:                           $env{'form.question:'.$i}).'</span>';
                   8502:           }
                   8503:        }
                   8504:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8505:     }
                   8506: # Start grading
1.415     www      8507:     my $pcorrect=$env{'form.pcorrect'};
                   8508:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8509:     my $storecount=0;
1.415     www      8510:     foreach my $key (keys(%env)) {
1.420     www      8511:        my $user='';
1.415     www      8512:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8513:           $user=$1;
                   8514:        }
                   8515:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8516:           my $id=$1;
                   8517:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8518:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8519:           } elsif ($env{'form.multi'.$id}) {
                   8520:              $user=$env{'form.multi'.$id};
1.420     www      8521:           }
                   8522:        }
                   8523:        if ($user) { 
1.415     www      8524:           my @answer=split(/\,/,$env{$key});
                   8525:           my $sum=0;
                   8526:           for (my $i=0;$i<$number;$i++) {
                   8527:              if ($answer[$i]) {
                   8528:                 if ($gradingmechanism eq 'attendance') {
                   8529:                    $sum+=$pcorrect;
                   8530:                 } else {
                   8531:                    if ($answer[$i] eq $correct[$i]) {
                   8532:                       $sum+=$pcorrect;
                   8533:                    } else {
                   8534:                       $sum+=$pincorrect;
                   8535:                    }
                   8536:                 }
                   8537:              }
                   8538:           }
1.416     www      8539:           my $ave=$sum/(100*$number);
                   8540: # Store
                   8541:           my ($username,$domain)=split(/\:/,$user);
                   8542:           my %grades=();
                   8543:           $grades{"resource.$part.solved"}='correct_by_override';
                   8544:           $grades{"resource.$part.awarded"}=$ave;
                   8545:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8546:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8547:                                                  $env{'request.course.id'},
                   8548:                                                  $domain,$username);
                   8549:           if ($returncode ne 'ok') {
                   8550:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8551:           } else {
                   8552:              $storecount++;
                   8553:           }
1.415     www      8554:        }
                   8555:     }
                   8556: # We are done
1.416     www      8557:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8558:              '</td></tr></table>'."\n".
1.414     www      8559:              '</td></tr></table><br /><br />'."\n";
                   8560:     return $result.&show_grading_menu_form($symb);
                   8561: }
                   8562: 
1.1       albertel 8563: sub handler {
1.41      ng       8564:     my $request=$_[0];
1.434     albertel 8565:     &reset_caches();
1.257     albertel 8566:     if ($env{'browser.mathml'}) {
1.141     www      8567: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8568:     } else {
1.141     www      8569: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8570:     }
                   8571:     $request->send_http_header;
1.44      ng       8572:     return '' if $request->header_only;
1.41      ng       8573:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8574:     my $symb=&get_symb($request,1);
1.160     albertel 8575:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8576:     my $command=$commands[0];
1.447     foxr     8577: 
1.160     albertel 8578:     if ($#commands > 0) {
                   8579: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8580:     }
1.447     foxr     8581: 
1.513     foxr     8582:     $ssi_error = 0;
1.353     albertel 8583:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8584:     if ($symb eq '' && $command eq '') {
1.257     albertel 8585: 	if ($env{'user.adv'}) {
                   8586: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8587: 		($env{'form.codethree'})) {
                   8588: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8589: 		    $env{'form.codethree'};
1.41      ng       8590: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8591: 		    &Apache::lonnet::checkin($token);
                   8592: 		if ($tsymb) {
1.137     albertel 8593: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8594: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     8595: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 8596: 					  ('grade_username' => $tuname,
                   8597: 					   'grade_domain' => $tudom,
                   8598: 					   'grade_courseid' => $tcrsid,
                   8599: 					   'grade_symb' => $tsymb)));
1.41      ng       8600: 		    } else {
1.45      ng       8601: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8602: 		    }
1.41      ng       8603: 		} else {
1.45      ng       8604: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8605: 		}
1.14      www      8606: 	    } else {
1.41      ng       8607: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8608: 	    }
                   8609: 	}
                   8610:     } else {
1.285     albertel 8611: 	&init_perm();
1.104     albertel 8612: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8613: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8614: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8615: 	    &pickStudentPage($request);
1.103     albertel 8616: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8617: 	    &displayPage($request);
1.104     albertel 8618: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8619: 	    &updateGradeByPage($request);
1.104     albertel 8620: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8621: 	    &processGroup($request);
1.104     albertel 8622: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8623: 	    $request->print(&grading_menu($request));
                   8624: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8625: 	    $request->print(&submit_options($request));
1.104     albertel 8626: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8627: 	    $request->print(&viewgrades($request));
1.104     albertel 8628: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8629: 	    $request->print(&processHandGrade($request));
1.106     albertel 8630: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8631: 	    $request->print(&editgrades($request));
1.106     albertel 8632: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8633: 	    $request->print(&verifyreceipt($request));
1.400     www      8634:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8635:             $request->print(&process_clicker($request));
                   8636:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8637:             $request->print(&process_clicker_file($request));
1.414     www      8638:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8639:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8640: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8641: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8642: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8643: 	    $request->print(&csvupload($request));
1.106     albertel 8644: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8645: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8646: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8647: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8648: 		$request->print(&csvuploadoptions($request));
1.41      ng       8649: 	    } else {
1.257     albertel 8650: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8651: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8652: 		} else {
1.257     albertel 8653: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8654: 		}
                   8655: 		$request->print(&csvuploadmap($request));
                   8656: 	    }
1.246     albertel 8657: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8658: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8659: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 8660: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8661:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8662:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8663: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8664: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8665: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8666: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8667:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8668:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8669: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8670:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8671:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8672:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8673: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8674:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8675:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8676: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8677:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8678: 	} elsif ($command) {
1.157     albertel 8679: 	    $request->print("Access Denied ($command)");
1.26      albertel 8680: 	}
1.2       albertel 8681:     }
1.513     foxr     8682:     if ($ssi_error) {
                   8683: 	&ssi_print_error($request);
                   8684:     }
1.353     albertel 8685:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8686:     &reset_caches();
1.44      ng       8687:     return '';
                   8688: }
                   8689: 
1.1       albertel 8690: 1;
                   8691: 
1.13      albertel 8692: __END__;

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