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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.528.2.12! raeburn     4: # $Id: grades.pm,v 1.528.2.11 2009/03/20 19:15:29 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.516     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.516     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.516     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.516     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.516     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.524     raeburn   243:     foreach my $partID (sort(keys(%$responseType))) {
                    244: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
1.375     albertel  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.528.2.11  raeburn   258: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
                    259:                      ' <span class="LC_internal_info">'.$resID.'</span></td>'.
                    260: 		     '<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
1.485     albertel  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 {
1.525     raeburn   281: 	my ($symb,$uname,$udom,$no_increment)=@_;
1.434     albertel  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.516     raeburn   288: 					   ('grade_target' => 'analyze',
                    289: 					    'grade_domain' => $udom,
                    290: 					    'grade_symb' => $symb,
                    291: 					    'grade_courseid' => 
                    292: 					    $env{'request.course.id'},
1.525     raeburn   293: 					    'grade_username' => $uname,
                    294:                                             'grade_noincrement' => $no_increment));
1.434     albertel  295: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    296: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    297: 	return $analyze_cache{$key} = \%analyze;
                    298:     }
                    299: 
                    300:     sub get_order {
1.525     raeburn   301: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    302: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  303: 	return $analyze->{"$partid.$respid.shown"};
                    304:     }
                    305: 
                    306:     sub get_radiobutton_correct_foil {
                    307: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    308: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.528.2.11  raeburn   309:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    310:         if (ref($foils) eq 'ARRAY') {
                    311:             foreach my $foil (@{$foils}) {
                    312:                 if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    313:                     return $foil;
                    314:                 }
                    315:             }
                    316:         }
1.434     albertel  317:     }
1.148     albertel  318: }
1.434     albertel  319: 
1.118     ng        320: #--- Clean response type for display
1.335     albertel  321: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    322: #        response types only.
1.118     ng        323: sub cleanRecord {
1.336     albertel  324:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    325: 	$uname,$udom) = @_;
1.398     albertel  326:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  327:     if ($response =~ /^(option|rank)$/) {
                    328: 	my %answer=&Apache::lonnet::str2hash($answer);
                    329: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    330: 	my ($toprow,$bottomrow);
                    331: 	foreach my $foil (@$order) {
                    332: 	    if ($grading{$foil} == 1) {
                    333: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    334: 	    } else {
                    335: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    336: 	    }
1.398     albertel  337: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  338: 	}
                    339: 	return '<blockquote><table border="1">'.
1.466     albertel  340: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    341: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  342: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    343:     } elsif ($response eq 'match') {
                    344: 	my %answer=&Apache::lonnet::str2hash($answer);
                    345: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    346: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    347: 	my ($toprow,$middlerow,$bottomrow);
                    348: 	foreach my $foil (@$order) {
                    349: 	    my $item=shift(@items);
                    350: 	    if ($grading{$foil} == 1) {
                    351: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  352: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  353: 	    } else {
                    354: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  355: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  356: 	    }
1.398     albertel  357: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        358: 	}
1.126     ng        359: 	return '<blockquote><table border="1">'.
1.466     albertel  360: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    361: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  362: 	    $middlerow.'</tr>'.
1.466     albertel  363: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  364: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    365:     } elsif ($response eq 'radiobutton') {
                    366: 	my %answer=&Apache::lonnet::str2hash($answer);
                    367: 	my ($toprow,$bottomrow);
1.434     albertel  368: 	my $correct = 
                    369: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    370: 	foreach my $foil (@$order) {
1.148     albertel  371: 	    if (exists($answer{$foil})) {
1.434     albertel  372: 		if ($foil eq $correct) {
1.466     albertel  373: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  374: 		} else {
1.466     albertel  375: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  376: 		}
                    377: 	    } else {
1.466     albertel  378: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  379: 	    }
1.398     albertel  380: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  381: 	}
                    382: 	return '<blockquote><table border="1">'.
1.466     albertel  383: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    384: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  385: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    386:     } elsif ($response eq 'essay') {
1.257     albertel  387: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        388: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  389: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    390: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        391: 
1.257     albertel  392: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    393: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    394: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    395: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    396: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    397: 	    $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        398: 	}
1.166     albertel  399: 	$answer =~ s-\n-<br />-g;
                    400: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  401:     } elsif ( $response eq 'organic') {
                    402: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    403: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    404: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    405: 	return $result;
1.335     albertel  406:     } elsif ( $response eq 'Task') {
                    407: 	if ( $answer eq 'SUBMITTED') {
                    408: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  409: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  410: 	    return $result;
                    411: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    412: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    413: 			       keys(%{$record}));
                    414: 	    return join('<br />',($version,@matches));
                    415: 			       
                    416: 			       
                    417: 	} else {
                    418: 	    my $result =
                    419: 		'<p>'
                    420: 		.&mt('Overall result: [_1]',
                    421: 		     $record->{$version."resource.$respid.$partid.status"})
                    422: 		.'</p>';
                    423: 	    
                    424: 	    $result .= '<ul>';
                    425: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    426: 			     keys(%{$record}));
                    427: 	    foreach my $grade (sort(@grade)) {
                    428: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    429: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    430: 				     $dim, $record->{$grade}).
                    431: 			  '</li>';
                    432: 	    }
                    433: 	    $result.='</ul>';
                    434: 	    return $result;
                    435: 	}
1.440     albertel  436:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    437: 	$answer = 
                    438: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    439: 							      $answer);
1.122     ng        440:     }
1.118     ng        441:     return $answer;
                    442: }
                    443: 
                    444: #-- A couple of common js functions
                    445: sub commonJSfunctions {
                    446:     my $request = shift;
                    447:     $request->print(<<COMMONJSFUNCTIONS);
                    448: <script type="text/javascript" language="javascript">
                    449:     function radioSelection(radioButton) {
                    450: 	var selection=null;
                    451: 	if (radioButton.length > 1) {
                    452: 	    for (var i=0; i<radioButton.length; i++) {
                    453: 		if (radioButton[i].checked) {
                    454: 		    return radioButton[i].value;
                    455: 		}
                    456: 	    }
                    457: 	} else {
                    458: 	    if (radioButton.checked) return radioButton.value;
                    459: 	}
                    460: 	return selection;
                    461:     }
                    462: 
                    463:     function pullDownSelection(selectOne) {
                    464: 	var selection="";
                    465: 	if (selectOne.length > 1) {
                    466: 	    for (var i=0; i<selectOne.length; i++) {
                    467: 		if (selectOne[i].selected) {
                    468: 		    return selectOne[i].value;
                    469: 		}
                    470: 	    }
                    471: 	} else {
1.138     albertel  472:             // only one value it must be the selected one
                    473: 	    return selectOne.value;
1.118     ng        474: 	}
                    475:     }
                    476: </script>
                    477: COMMONJSFUNCTIONS
                    478: }
                    479: 
1.44      ng        480: #--- Dumps the class list with usernames,list of sections,
                    481: #--- section, ids and fullnames for each user.
                    482: sub getclasslist {
1.449     banghart  483:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  484:     my @getsec;
1.450     banghart  485:     my @getgroup;
1.442     banghart  486:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  487:     if (!ref($getsec)) {
                    488: 	if ($getsec ne '' && $getsec ne 'all') {
                    489: 	    @getsec=($getsec);
                    490: 	}
                    491:     } else {
                    492: 	@getsec=@{$getsec};
                    493:     }
                    494:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  495:     if (!ref($getgroup)) {
                    496: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    497: 	    @getgroup=($getgroup);
                    498: 	}
                    499:     } else {
                    500: 	@getgroup=@{$getgroup};
                    501:     }
                    502:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  503: 
1.449     banghart  504:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  505:     # Bail out if we were unable to get the classlist
1.56      matthew   506:     return if (! defined($classlist));
1.449     banghart  507:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   508:     #
                    509:     my %sections;
                    510:     my %fullnames;
1.205     matthew   511:     foreach my $student (keys(%$classlist)) {
                    512:         my $end      = 
                    513:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    514:         my $start    = 
                    515:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    516:         my $id       = 
                    517:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    518:         my $section  = 
                    519:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    520:         my $fullname = 
                    521:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    522:         my $status   = 
                    523:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  524:         my $group   = 
                    525:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        526: 	# filter students according to status selected
1.442     banghart  527: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    528: 	    if (!($stu_status =~ $status)) {
1.450     banghart  529: 		delete($classlist->{$student});
1.76      ng        530: 		next;
                    531: 	    }
                    532: 	}
1.450     banghart  533: 	# filter students according to groups selected
1.453     banghart  534: 	my @stu_groups = split(/,/,$group);
1.450     banghart  535: 	if (@getgroup) {
                    536: 	    my $exclude = 1;
1.454     banghart  537: 	    foreach my $grp (@getgroup) {
                    538: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  539: 	            if ($stu_group eq $grp) {
                    540: 	                $exclude = 0;
                    541:     	            } 
1.450     banghart  542: 	        }
1.453     banghart  543:     	        if (($grp eq 'none') && !$group) {
                    544:         	        $exclude = 0;
                    545:         	}
1.450     banghart  546: 	    }
                    547: 	    if ($exclude) {
                    548: 	        delete($classlist->{$student});
                    549: 	    }
                    550: 	}
1.205     matthew   551: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  552: 	if (&canview($section)) {
1.291     albertel  553: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  554: 		$sections{$section}++;
1.450     banghart  555: 		if ($classlist->{$student}) {
                    556: 		    $fullnames{$student}=$fullname;
                    557: 		}
1.103     albertel  558: 	    } else {
1.205     matthew   559: 		delete($classlist->{$student});
1.103     albertel  560: 	    }
                    561: 	} else {
1.205     matthew   562: 	    delete($classlist->{$student});
1.103     albertel  563: 	}
1.44      ng        564:     }
                    565:     my %seen = ();
1.56      matthew   566:     my @sections = sort(keys(%sections));
                    567:     return ($classlist,\@sections,\%fullnames);
1.44      ng        568: }
                    569: 
1.103     albertel  570: sub canmodify {
                    571:     my ($sec)=@_;
                    572:     if ($perm{'mgr'}) {
                    573: 	if (!defined($perm{'mgr_section'})) {
                    574: 	    # can modify whole class
                    575: 	    return 1;
                    576: 	} else {
                    577: 	    if ($sec eq $perm{'mgr_section'}) {
                    578: 		#can modify the requested section
                    579: 		return 1;
                    580: 	    } else {
                    581: 		# can't modify the request section
                    582: 		return 0;
                    583: 	    }
                    584: 	}
                    585:     }
                    586:     #can't modify
                    587:     return 0;
                    588: }
                    589: 
                    590: sub canview {
                    591:     my ($sec)=@_;
                    592:     if ($perm{'vgr'}) {
                    593: 	if (!defined($perm{'vgr_section'})) {
                    594: 	    # can modify whole class
                    595: 	    return 1;
                    596: 	} else {
                    597: 	    if ($sec eq $perm{'vgr_section'}) {
                    598: 		#can modify the requested section
                    599: 		return 1;
                    600: 	    } else {
                    601: 		# can't modify the request section
                    602: 		return 0;
                    603: 	    }
                    604: 	}
                    605:     }
                    606:     #can't modify
                    607:     return 0;
                    608: }
                    609: 
1.44      ng        610: #--- Retrieve the grade status of a student for all the parts
                    611: sub student_gradeStatus {
1.324     albertel  612:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  613:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        614:     my %partstatus = ();
                    615:     foreach (@$partlist) {
1.128     ng        616: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        617: 	$status              = 'nothing' if ($status eq '');
                    618: 	$partstatus{$_}      = $status;
                    619: 	my $subkey           = "resource.$_.submitted_by";
                    620: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    621:     }
                    622:     return %partstatus;
                    623: }
                    624: 
1.45      ng        625: # hidden form and javascript that calls the form
                    626: # Use by verifyscript and viewgrades
                    627: # Shows a student's view of problem and submission
                    628: sub jscriptNform {
1.324     albertel  629:     my ($symb) = @_;
1.442     banghart  630:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        631:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    632: 	'    function viewOneStudent(user,domain) {'."\n".
                    633: 	'	document.onestudent.student.value = user;'."\n".
                    634: 	'	document.onestudent.userdom.value = domain;'."\n".
                    635: 	'	document.onestudent.submit();'."\n".
                    636: 	'    }'."\n".
                    637: 	'</script>'."\n";
                    638:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  639: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  640: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    641: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  642: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        643: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    644: 	'<input type="hidden" name="student" value="" />'."\n".
                    645: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    646: 	'</form>'."\n";
                    647:     return $jscript;
                    648: }
1.39      ng        649: 
1.447     foxr      650: 
                    651: 
1.315     bowersj2  652: # Given the score (as a number [0-1] and the weight) what is the final
                    653: # point value? This function will round to the nearest tenth, third,
                    654: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  655: sub compute_points {
1.315     bowersj2  656:     my ($score, $weight) = @_;
                    657:     
                    658:     my $tolerance = .00001;
                    659:     my $points = $score * $weight;
                    660: 
                    661:     # Check for nearness to 1/x.
                    662:     my $check_for_nearness = sub {
                    663:         my ($factor) = @_;
                    664:         my $num = ($points * $factor) + $tolerance;
                    665:         my $floored_num = floor($num);
1.316     albertel  666:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  667:             return $floored_num / $factor;
                    668:         }
                    669:         return $points;
                    670:     };
                    671: 
                    672:     $points = $check_for_nearness->(10);
                    673:     $points = $check_for_nearness->(3);
                    674:     $points = $check_for_nearness->(4);
                    675:     
                    676:     return $points;
                    677: }
                    678: 
1.44      ng        679: #------------------ End of general use routines --------------------
1.87      www       680: 
                    681: #
                    682: # Find most similar essay
                    683: #
                    684: 
                    685: sub most_similar {
1.426     albertel  686:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       687: 
                    688: # ignore spaces and punctuation
                    689: 
                    690:     $uessay=~s/\W+/ /gs;
                    691: 
1.282     www       692: # ignore empty submissions (occuring when only files are sent)
                    693: 
                    694:     unless ($uessay=~/\w+/) { return ''; }
                    695: 
1.87      www       696: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       697:     my $limit=0.6;
1.87      www       698:     my $sname='';
                    699:     my $sdom='';
                    700:     my $scrsid='';
                    701:     my $sessay='';
                    702: # go through all essays ...
1.426     albertel  703:     foreach my $tkey (keys(%$old_essays)) {
                    704: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       705: # ... except the same student
1.426     albertel  706:         next if (($tname eq $uname) && ($tdom eq $udom));
                    707: 	my $tessay=$old_essays->{$tkey};
                    708: 	$tessay=~s/\W+/ /gs;
1.87      www       709: # String similarity gives up if not even limit
1.426     albertel  710: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       711: # Found one
1.426     albertel  712: 	if ($tsimilar>$limit) {
                    713: 	    $limit=$tsimilar;
                    714: 	    $sname=$tname;
                    715: 	    $sdom=$tdom;
                    716: 	    $scrsid=$tcrsid;
                    717: 	    $sessay=$old_essays->{$tkey};
                    718: 	}
1.87      www       719:     }
1.88      www       720:     if ($limit>0.6) {
1.87      www       721:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    722:     } else {
                    723:        return ('','','','',0);
                    724:     }
                    725: }
                    726: 
1.44      ng        727: #-------------------------------------------------------------------
                    728: 
                    729: #------------------------------------ Receipt Verification Routines
1.45      ng        730: #
1.44      ng        731: #--- Check whether a receipt number is valid.---
                    732: sub verifyreceipt {
                    733:     my $request  = shift;
                    734: 
1.257     albertel  735:     my $courseid = $env{'request.course.id'};
1.184     www       736:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  737: 	$env{'form.receipt'};
1.44      ng        738:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  739:     my ($symb)   = &get_symb($request);
1.44      ng        740: 
1.487     albertel  741:     my $title.=
                    742: 	'<h3><span class="LC_info">'.
1.528.2.11  raeburn   743: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  744: 	'</span></h3>'."\n".
                    745: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    746: 	'</h4>'."\n";
1.44      ng        747: 
                    748:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   749:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  750:     
                    751:     my $receiptparts=0;
1.390     albertel  752:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    753: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  754:     my $parts=['0'];
1.324     albertel  755:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.486     albertel  756:     
                    757:     my $header = 
                    758: 	&Apache::loncommon::start_data_table().
                    759: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  760: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    761: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    762: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  763:     if ($receiptparts) {
1.487     albertel  764: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  765:     }
                    766:     $header.=
                    767: 	&Apache::loncommon::end_data_table_header_row();
                    768: 
1.294     albertel  769:     foreach (sort 
                    770: 	     {
                    771: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    772: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    773: 		 }
                    774: 		 return $a cmp $b;
                    775: 	     } (keys(%$fullname))) {
1.44      ng        776: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  777: 	foreach my $part (@$parts) {
                    778: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  779: 		$contents.=
                    780: 		    &Apache::loncommon::start_data_table_row().
                    781: 		    '<td>&nbsp;'."\n".
1.177     albertel  782: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  783: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  784: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    785: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    786: 		if ($receiptparts) {
                    787: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    788: 		}
1.486     albertel  789: 		$contents.= 
                    790: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  791: 		
                    792: 		$matches++;
                    793: 	    }
1.44      ng        794: 	}
                    795:     }
                    796:     if ($matches == 0) {
1.487     albertel  797: 	$string = $title.&mt('No match found for the above receipt.');
1.44      ng        798:     } else {
1.324     albertel  799: 	$string = &jscriptNform($symb).$title.
1.487     albertel  800: 	    '<p>'.
                    801: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
                    802: 	    '</p>'.
1.486     albertel  803: 	    $header.
                    804: 	    $contents.
                    805: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        806:     }
1.324     albertel  807:     return $string.&show_grading_menu_form($symb);
1.44      ng        808: }
                    809: 
                    810: #--- This is called by a number of programs.
                    811: #--- Called from the Grading Menu - View/Grade an individual student
                    812: #--- Also called directly when one clicks on the subm button 
                    813: #    on the problem page.
1.30      ng        814: sub listStudents {
1.41      ng        815:     my ($request) = shift;
1.49      albertel  816: 
1.324     albertel  817:     my ($symb) = &get_symb($request);
1.257     albertel  818:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    819:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    820:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  821:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  822:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    823:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    824:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    825: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  826: 
1.485     albertel  827:     my $result='<h3><span class="LC_info">&nbsp;'.
1.528.2.11  raeburn   828: 	&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  829: 	.'</span></h3>';
1.118     ng        830: 
1.324     albertel  831:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  832: 
1.528.2.11  raeburn   833:     my %lt = &Apache::lonlocal::texthash (
                    834:                 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    835:                 'single'   => 'Please select the student before clicking on the Next button.',
                    836:              );
1.45      ng        837:     $request->print(<<LISTJAVASCRIPT);
                    838: <script type="text/javascript" language="javascript">
1.110     ng        839:     function checkSelect(checkBox) {
                    840: 	var ctr=0;
                    841: 	var sense="";
                    842: 	if (checkBox.length > 1) {
                    843: 	    for (var i=0; i<checkBox.length; i++) {
                    844: 		if (checkBox[i].checked) {
                    845: 		    ctr++;
                    846: 		}
                    847: 	    }
1.485     albertel  848: 	    sense = '$lt{'multiple'}';
1.110     ng        849: 	} else {
                    850: 	    if (checkBox.checked) {
                    851: 		ctr = 1;
                    852: 	    }
1.485     albertel  853: 	    sense = '$lt{'single'}';
1.110     ng        854: 	}
                    855: 	if (ctr == 0) {
1.485     albertel  856: 	    alert(sense);
1.110     ng        857: 	    return false;
                    858: 	}
                    859: 	document.gradesub.submit();
                    860:     }
                    861: 
                    862:     function reLoadList(formname) {
1.112     ng        863: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        864: 	formname.command.value = 'submission';
                    865: 	formname.submit();
                    866:     }
1.45      ng        867: </script>
                    868: LISTJAVASCRIPT
                    869: 
1.118     ng        870:     &commonJSfunctions($request);
1.41      ng        871:     $request->print($result);
1.39      ng        872: 
1.401     albertel  873:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    874:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  875:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  876: 	"\n".$table;
                    877: 	
                    878:     $gradeTable .= 
1.528.2.11  raeburn   879: 	'&nbsp;<b>'.&mt('View Problem Text').': </b>'.
1.485     albertel  880: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                    881: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
1.528.2.11  raeburn   882: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n";
1.485     albertel  883:     $gradeTable .= 
1.528.2.11  raeburn   884: 	'&nbsp;<b>'.&mt('View Answer').': </b>'.
1.485     albertel  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".
1.528.2.11  raeburn   887: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n";
1.485     albertel  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 .= 
1.528.2.11  raeburn   903: 	'&nbsp;<b>'.&mt('Submissions').': </b>'.$submission_options.'<br />'."\n";
1.485     albertel  904: 
                    905:     $gradeTable .= 
1.528.2.11  raeburn   906:         '&nbsp;<b>'.&mt('Grading Increments').': </b>'.
1.485     albertel  907: 	    '<select name="increment">'.
                    908: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
                    909: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
                    910: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
                    911: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
1.528.2.11  raeburn   912: 	    '</select>';
1.485     albertel  913:     
                    914:     $gradeTable .= 
1.432     banghart  915:         &build_section_inputs().
1.45      ng        916: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  917: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    918: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    919: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    920: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  921: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        922: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    923: 
1.257     albertel  924:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  925: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        926:     } else {
1.485     albertel  927: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
                    928: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
1.124     ng        929:     }
1.112     ng        930: 
1.528.2.11  raeburn   931:     $gradeTable.=&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.").'<br />'."\n".
1.110     ng        932: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  933: 
                    934: # checkall buttons
                    935:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        936:     $gradeTable.='<input type="button" '."\n".
1.45      ng        937: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.528.2.11  raeburn   938: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  939:     $gradeTable.=&check_buttons();
1.485     albertel  940:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
1.450     banghart  941:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  942:     $gradeTable.= &Apache::loncommon::start_data_table().
                    943: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        944:     my $loop = 0;
                    945:     while ($loop < 2) {
1.485     albertel  946: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    947: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  948: 	if ($env{'form.showgrading'} eq 'yes' 
                    949: 	    && $submitonly ne 'queued'
                    950: 	    && $submitonly ne 'all') {
1.485     albertel  951: 	    foreach my $part (sort(@$partlist)) {
                    952: 		my $display_part=
                    953: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    954: 		$gradeTable.=
                    955: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        956: 	    }
1.301     albertel  957: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  958: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        959: 	}
                    960: 	$loop++;
1.126     ng        961: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        962:     }
1.474     albertel  963:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        964: 
1.45      ng        965:     my $ctr = 0;
1.294     albertel  966:     foreach my $student (sort 
                    967: 			 {
                    968: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    969: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    970: 			     }
                    971: 			     return $a cmp $b;
                    972: 			 }
                    973: 			 (keys(%$fullname))) {
1.41      ng        974: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  975: 
1.110     ng        976: 	my %status = ();
1.301     albertel  977: 
                    978: 	if ($submitonly eq 'queued') {
                    979: 	    my %queue_status = 
                    980: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    981: 							$udom,$uname);
                    982: 	    next if (!defined($queue_status{'gradingqueue'}));
                    983: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    984: 	}
                    985: 
                    986: 	if ($env{'form.showgrading'} eq 'yes' 
                    987: 	    && $submitonly ne 'queued'
                    988: 	    && $submitonly ne 'all') {
1.324     albertel  989: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  990: 	    my $submitted = 0;
1.164     albertel  991: 	    my $graded = 0;
1.248     albertel  992: 	    my $incorrect = 0;
1.110     ng        993: 	    foreach (keys(%status)) {
1.145     albertel  994: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  995: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    996: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    997: 		
1.110     ng        998: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    999: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1000: 		    $submitted = 0;
1.150     albertel 1001: 		    my ($part)=split(/\./,$partid);
1.110     ng       1002: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1003: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1004: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1005: 		}
1.41      ng       1006: 	    }
1.248     albertel 1007: 	    
1.156     albertel 1008: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1009: 				     $submitonly eq 'incorrect' ||
                   1010: 				     $submitonly eq 'graded'));
1.248     albertel 1011: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1012: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1013: 	}
1.34      ng       1014: 
1.45      ng       1015: 	$ctr++;
1.249     albertel 1016: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1017:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1018: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1019: 	    if ($ctr%2 ==1) {
                   1020: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1021: 	    }
1.126     ng       1022: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel 1023:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                   1024:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1025: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1026: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1027: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1028: 
1.257     albertel 1029: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1030: 		foreach (sort(keys(%status))) {
1.485     albertel 1031: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1032: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1033: 		}
1.41      ng       1034: 	    }
1.126     ng       1035: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1036: 	    if ($ctr%2 ==0) {
                   1037: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1038: 	    }
1.41      ng       1039: 	}
                   1040:     }
1.110     ng       1041:     if ($ctr%2 ==1) {
1.126     ng       1042: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1043: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1044: 		&& $submitonly ne 'queued'
                   1045: 		&& $submitonly ne 'all') {
1.110     ng       1046: 		foreach (@$partlist) {
                   1047: 		    $gradeTable.='<td>&nbsp;</td>';
                   1048: 		}
1.301     albertel 1049: 	    } elsif ($submitonly eq 'queued') {
                   1050: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1051: 	    }
1.474     albertel 1052: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1053:     }
                   1054: 
1.474     albertel 1055:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1056: 	'<input type="button" '.
                   1057: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.528.2.11  raeburn  1058: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1059:     if ($ctr == 0) {
1.96      albertel 1060: 	my $num_students=(scalar(keys(%$fullname)));
                   1061: 	if ($num_students eq 0) {
1.485     albertel 1062: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1063: 	} else {
1.171     albertel 1064: 	    my $submissions='submissions';
                   1065: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1066: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1067: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1068: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1069: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1070: 		    $num_students).
                   1071: 		'</span><br />';
1.96      albertel 1072: 	}
1.46      ng       1073:     } elsif ($ctr == 1) {
1.474     albertel 1074: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1075:     }
1.324     albertel 1076:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1077:     $request->print($gradeTable);
1.44      ng       1078:     return '';
1.10      ng       1079: }
                   1080: 
1.44      ng       1081: #---- Called from the listStudents routine
1.249     albertel 1082: 
                   1083: sub check_script {
                   1084:     my ($form, $type)=@_;
                   1085:     my $chkallscript='<script type="text/javascript">
                   1086:     function checkall() {
                   1087:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1088:             ele = document.forms.'.$form.'.elements[i];
                   1089:             if (ele.name == "'.$type.'") {
                   1090:             document.forms.'.$form.'.elements[i].checked=true;
                   1091:                                        }
                   1092:         }
                   1093:     }
                   1094: 
                   1095:     function checksec() {
                   1096:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1097:             ele = document.forms.'.$form.'.elements[i];
                   1098:            string = document.forms.'.$form.'.chksec.value;
                   1099:            if
                   1100:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1101:               document.forms.'.$form.'.elements[i].checked=true;
                   1102:             }
                   1103:         }
                   1104:     }
                   1105: 
                   1106: 
                   1107:     function uncheckall() {
                   1108:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1109:             ele = document.forms.'.$form.'.elements[i];
                   1110:             if (ele.name == "'.$type.'") {
                   1111:             document.forms.'.$form.'.elements[i].checked=false;
                   1112:                                        }
                   1113:         }
                   1114:     }
                   1115: 
                   1116: </script>'."\n";
                   1117:     return $chkallscript;
                   1118: }
                   1119: 
                   1120: sub check_buttons {
1.485     albertel 1121:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1122:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1123:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1124:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1125:     return $buttons;
                   1126: }
                   1127: 
1.44      ng       1128: #     Displays the submissions for one student or a group of students
1.34      ng       1129: sub processGroup {
1.41      ng       1130:     my ($request)  = shift;
                   1131:     my $ctr        = 0;
1.155     albertel 1132:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1133:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1134: 
1.396     banghart 1135:     foreach my $student (@stuchecked) {
                   1136: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1137: 	$env{'form.student'}        = $uname;
                   1138: 	$env{'form.userdom'}        = $udom;
                   1139: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1140: 	&submission($request,$ctr,$total);
                   1141: 	$ctr++;
                   1142:     }
                   1143:     return '';
1.35      ng       1144: }
1.34      ng       1145: 
1.44      ng       1146: #------------------------------------------------------------------------------------
                   1147: #
                   1148: #-------------------------- Next few routines handles grading by student, essentially
                   1149: #                           handles essay response type problem/part
                   1150: #
                   1151: #--- Javascript to handle the submission page functionality ---
                   1152: sub sub_page_js {
                   1153:     my $request = shift;
1.528.2.11  raeburn  1154:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.44      ng       1155:     $request->print(<<SUBJAVASCRIPT);
                   1156: <script type="text/javascript" language="javascript">
1.71      ng       1157:     function updateRadio(formname,id,weight) {
1.125     ng       1158: 	var gradeBox = formname["GD_BOX"+id];
                   1159: 	var radioButton = formname["RADVAL"+id];
                   1160: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1161: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1162: 	gradeBox.value = pts;
                   1163: 	var resetbox = false;
                   1164: 	if (isNaN(pts) || pts < 0) {
1.528.2.11  raeburn  1165: 	    alert("$alertmsg"+pts);
1.71      ng       1166: 	    for (var i=0; i<radioButton.length; i++) {
                   1167: 		if (radioButton[i].checked) {
                   1168: 		    gradeBox.value = i;
                   1169: 		    resetbox = true;
                   1170: 		}
                   1171: 	    }
                   1172: 	    if (!resetbox) {
                   1173: 		formtextbox.value = "";
                   1174: 	    }
                   1175: 	    return;
1.44      ng       1176: 	}
1.71      ng       1177: 
                   1178: 	if (pts > weight) {
                   1179: 	    var resp = confirm("You entered a value ("+pts+
                   1180: 			       ") greater than the weight for the part. Accept?");
                   1181: 	    if (resp == false) {
1.125     ng       1182: 		gradeBox.value = oldpts;
1.71      ng       1183: 		return;
                   1184: 	    }
1.44      ng       1185: 	}
1.13      albertel 1186: 
1.71      ng       1187: 	for (var i=0; i<radioButton.length; i++) {
                   1188: 	    radioButton[i].checked=false;
                   1189: 	    if (pts == i && pts != "") {
                   1190: 		radioButton[i].checked=true;
                   1191: 	    }
                   1192: 	}
                   1193: 	updateSelect(formname,id);
1.125     ng       1194: 	formname["stores"+id].value = "0";
1.41      ng       1195:     }
1.5       albertel 1196: 
1.72      ng       1197:     function writeBox(formname,id,pts) {
1.125     ng       1198: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1199: 	if (checkSolved(formname,id) == 'update') {
                   1200: 	    gradeBox.value = pts;
                   1201: 	} else {
1.125     ng       1202: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1203: 	    gradeBox.value = oldpts;
1.125     ng       1204: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1205: 	    for (var i=0; i<radioButton.length; i++) {
                   1206: 		radioButton[i].checked=false;
1.72      ng       1207: 		if (i == oldpts) {
1.71      ng       1208: 		    radioButton[i].checked=true;
                   1209: 		}
                   1210: 	    }
1.41      ng       1211: 	}
1.125     ng       1212: 	formname["stores"+id].value = "0";
1.71      ng       1213: 	updateSelect(formname,id);
                   1214: 	return;
1.41      ng       1215:     }
1.44      ng       1216: 
1.71      ng       1217:     function clearRadBox(formname,id) {
                   1218: 	if (checkSolved(formname,id) == 'noupdate') {
                   1219: 	    updateSelect(formname,id);
                   1220: 	    return;
                   1221: 	}
1.125     ng       1222: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1223: 	for (var i=0; i<gradeSelect.length; i++) {
                   1224: 	    if (gradeSelect[i].selected) {
                   1225: 		var selectx=i;
                   1226: 	    }
                   1227: 	}
1.125     ng       1228: 	var stores = formname["stores"+id];
1.71      ng       1229: 	if (selectx == stores.value) { return };
1.125     ng       1230: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1231: 	gradeBox.value = "";
1.125     ng       1232: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1233: 	for (var i=0; i<radioButton.length; i++) {
                   1234: 	    radioButton[i].checked=false;
                   1235: 	}
                   1236: 	stores.value = selectx;
                   1237:     }
1.5       albertel 1238: 
1.71      ng       1239:     function checkSolved(formname,id) {
1.125     ng       1240: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1241: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1242: 	    if (!reply) {return "noupdate";}
1.120     ng       1243: 	    formname.overRideScore.value = 'yes';
1.41      ng       1244: 	}
1.71      ng       1245: 	return "update";
1.13      albertel 1246:     }
1.71      ng       1247: 
                   1248:     function updateSelect(formname,id) {
1.125     ng       1249: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1250: 	return;
1.41      ng       1251:     }
1.33      ng       1252: 
1.121     ng       1253: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1254:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1255: 	formname.gradeOpt.value = val;
1.71      ng       1256: 	if (val == "Save & Next") {
                   1257: 	    for (i=0;i<=total;i++) {
                   1258: 		for (j=0;j<parttot;j++) {
1.125     ng       1259: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1260: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1261: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1262: 			if (points == "") {
1.125     ng       1263: 			    var name = formname["name"+i].value;
1.129     ng       1264: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1265: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1266: 					       ", part "+partid+". Continue?");
1.71      ng       1267: 			    if (resp == false) {
1.125     ng       1268: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1269: 				return false;
                   1270: 			    }
                   1271: 			}
                   1272: 		    }
                   1273: 		    
                   1274: 		}
                   1275: 	    }
                   1276: 	    
                   1277: 	}
1.121     ng       1278: 	if (val == "Grade Student") {
                   1279: 	    formname.showgrading.value = "yes";
                   1280: 	    if (formname.Status.value == "") {
                   1281: 		formname.Status.value = "Active";
                   1282: 	    }
                   1283: 	    formname.studentNo.value = total;
                   1284: 	}
1.120     ng       1285: 	formname.submit();
                   1286:     }
                   1287: 
1.71      ng       1288: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1289:     function checkSubmitPage(formname,total) {
                   1290: 	noscore = new Array(100);
                   1291: 	var ptr = 0;
                   1292: 	for (i=1;i<total;i++) {
1.125     ng       1293: 	    var partid = formname["q_"+i].value;
1.127     ng       1294: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1295: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1296: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1297: 		if (points == "" && status != "correct_by_student") {
                   1298: 		    noscore[ptr] = i;
                   1299: 		    ptr++;
                   1300: 		}
                   1301: 	    }
                   1302: 	}
                   1303: 	if (ptr != 0) {
                   1304: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1305: 	    var prolist = "";
                   1306: 	    if (ptr == 1) {
                   1307: 		prolist = noscore[0];
                   1308: 	    } else {
                   1309: 		var i = 0;
                   1310: 		while (i < ptr-1) {
                   1311: 		    prolist += noscore[i]+", ";
                   1312: 		    i++;
                   1313: 		}
                   1314: 		prolist += "and "+noscore[i];
                   1315: 	    }
                   1316: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1317: 	    if (resp == false) {
                   1318: 		return false;
                   1319: 	    }
                   1320: 	}
1.45      ng       1321: 
1.71      ng       1322: 	formname.submit();
                   1323:     }
                   1324: </script>
                   1325: SUBJAVASCRIPT
                   1326: }
1.45      ng       1327: 
1.71      ng       1328: #--- javascript for essay type problem --
                   1329: sub sub_page_kw_js {
                   1330:     my $request = shift;
1.80      ng       1331:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1332:     &commonJSfunctions($request);
1.350     albertel 1333: 
1.351     albertel 1334:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1335:     <script text="text/javascript">
                   1336:     function checkInput() {
                   1337:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1338:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1339:       var usrctr = document.msgcenter.usrctr.value;
                   1340:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1341:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1342: 
                   1343:       var msgchk = "";
                   1344:       if (document.msgcenter.subchk.checked) {
                   1345:          msgchk = "msgsub,";
                   1346:       }
                   1347:       var includemsg = 0;
                   1348:       for (var i=1; i<=nmsg; i++) {
                   1349:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1350:           var frmmsg = document.msgcenter["msg"+i];
                   1351:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1352:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1353:           showflg.value = "1";
                   1354:           var chkbox = document.msgcenter["msgn"+i];
                   1355:           if (chkbox.checked) {
                   1356:              msgchk += "savemsg"+i+",";
                   1357:              includemsg = 1;
                   1358:           }
                   1359:       }
                   1360:       if (document.msgcenter.newmsgchk.checked) {
                   1361:          msgchk += "newmsg"+usrctr;
                   1362:          includemsg = 1;
                   1363:       }
                   1364:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1365:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1366:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1367:       includemsg.value = msgchk;
                   1368: 
                   1369:       self.close()
                   1370: 
                   1371:     }
                   1372:     </script>
                   1373: INNERJS
                   1374: 
1.351     albertel 1375:     my $inner_js_highlight_central=<<INNERJS;
                   1376:  <script type="text/javascript">
                   1377:     function updateChoice(flag) {
                   1378:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1379:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1380:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1381:       opener.document.SCORE.refresh.value = "on";
                   1382:       if (opener.document.SCORE.keywords.value!=""){
                   1383:          opener.document.SCORE.submit();
                   1384:       }
                   1385:       self.close()
                   1386:     }
                   1387: </script>
                   1388: INNERJS
                   1389: 
                   1390:     my $start_page_msg_central = 
                   1391:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1392: 				       {'js_ready'  => 1,
                   1393: 					'only_body' => 1,
                   1394: 					'bgcolor'   =>'#FFFFFF',});
                   1395:     my $end_page_msg_central = 
                   1396: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1397: 
                   1398: 
                   1399:     my $start_page_highlight_central = 
                   1400:         &Apache::loncommon::start_page('Highlight Central',
                   1401: 				       $inner_js_highlight_central,
1.350     albertel 1402: 				       {'js_ready'  => 1,
                   1403: 					'only_body' => 1,
                   1404: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1405:     my $end_page_highlight_central = 
1.350     albertel 1406: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1407: 
1.219     www      1408:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1409:     $docopen=~s/^document\.//;
1.528.2.11  raeburn  1410:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.71      ng       1411:     $request->print(<<SUBJAVASCRIPT);
                   1412: <script type="text/javascript" language="javascript">
1.45      ng       1413: 
1.44      ng       1414: //===================== Show list of keywords ====================
1.122     ng       1415:   function keywords(formname) {
                   1416:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1417:     if (nret==null) return;
1.122     ng       1418:     formname.keywords.value = nret;
1.44      ng       1419: 
1.122     ng       1420:     if (formname.keywords.value != "") {
1.128     ng       1421: 	formname.refresh.value = "on";
1.122     ng       1422: 	formname.submit();
1.44      ng       1423:     }
                   1424:     return;
                   1425:   }
                   1426: 
                   1427: //===================== Script to view submitted by ==================
                   1428:   function viewSubmitter(submitter) {
                   1429:     document.SCORE.refresh.value = "on";
                   1430:     document.SCORE.NCT.value = "1";
                   1431:     document.SCORE.unamedom0.value = submitter;
                   1432:     document.SCORE.submit();
                   1433:     return;
                   1434:   }
                   1435: 
                   1436: //===================== Script to add keyword(s) ==================
                   1437:   function getSel() {
                   1438:     if (document.getSelection) txt = document.getSelection();
                   1439:     else if (document.selection) txt = document.selection.createRange().text;
                   1440:     else return;
                   1441:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1442:     if (cleantxt=="") {
1.528.2.11  raeburn  1443: 	alert("$alertmsg");
1.44      ng       1444: 	return;
                   1445:     }
                   1446:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1447:     if (nret==null) return;
1.127     ng       1448:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1449:     if (document.SCORE.keywords.value != "") {
1.127     ng       1450: 	document.SCORE.refresh.value = "on";
1.44      ng       1451: 	document.SCORE.submit();
                   1452:     }
                   1453:     return;
                   1454:   }
                   1455: 
                   1456: //====================== Script for composing message ==============
1.80      ng       1457:    // preload images
                   1458:    img1 = new Image();
                   1459:    img1.src = "$iconpath/mailbkgrd.gif";
                   1460:    img2 = new Image();
                   1461:    img2.src = "$iconpath/mailto.gif";
                   1462: 
1.44      ng       1463:   function msgCenter(msgform,usrctr,fullname) {
                   1464:     var Nmsg  = msgform.savemsgN.value;
                   1465:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1466:     var subject = msgform.msgsub.value;
1.127     ng       1467:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1468:     re = /msgsub/;
                   1469:     var shwsel = "";
                   1470:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1471:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1472:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1473:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1474: 	var testmsg = "savemsg"+i+",";
                   1475: 	re = new RegExp(testmsg,"g");
1.44      ng       1476: 	shwsel = "";
                   1477: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1478: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1479: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1480: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1481: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1482:     }
1.125     ng       1483:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1484:     shwsel = "";
                   1485:     re = /newmsg/;
                   1486:     if (re.test(msgchk)) { shwsel = "checked" }
                   1487:     newMsg(newmsg,shwsel);
                   1488:     msgTail(); 
                   1489:     return;
                   1490:   }
                   1491: 
1.123     ng       1492:   function checkEntities(strx) {
                   1493:     if (strx.length == 0) return strx;
                   1494:     var orgStr = ["&", "<", ">", '"']; 
                   1495:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1496:     var counter = 0;
                   1497:     while (counter < 4) {
                   1498: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1499: 	counter++;
                   1500:     }
                   1501:     return strx;
                   1502:   }
                   1503: 
                   1504:   function strReplace(strx, orgStr, newStr) {
                   1505:     return strx.split(orgStr).join(newStr);
                   1506:   }
                   1507: 
1.44      ng       1508:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1509:     var height = 70*Nmsg+250;
1.44      ng       1510:     var scrollbar = "no";
                   1511:     if (height > 600) {
                   1512: 	height = 600;
                   1513: 	scrollbar = "yes";
                   1514:     }
1.118     ng       1515:     var xpos = (screen.width-600)/2;
                   1516:     xpos = (xpos < 0) ? '0' : xpos;
                   1517:     var ypos = (screen.height-height)/2-30;
                   1518:     ypos = (ypos < 0) ? '0' : ypos;
                   1519: 
1.206     albertel 1520:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1521:     pWin.focus();
                   1522:     pDoc = pWin.document;
1.219     www      1523:     pDoc.$docopen;
1.351     albertel 1524:     pDoc.write('$start_page_msg_central');
1.76      ng       1525: 
                   1526:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1527:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1528:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1529: 
                   1530:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1531:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1532:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1533: }
                   1534:     function displaySubject(msg,shwsel) {
1.76      ng       1535:     pDoc = pWin.document;
                   1536:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1537:     pDoc.write("<td>Subject<\\/td>");
                   1538:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1539:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1540: }
                   1541: 
1.72      ng       1542:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1543:     pDoc = pWin.document;
                   1544:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1545:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1546:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1547:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1548: }
                   1549: 
                   1550:   function newMsg(newmsg,shwsel) {
1.76      ng       1551:     pDoc = pWin.document;
                   1552:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1553:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1554:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1555:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1556: }
                   1557: 
                   1558:   function msgTail() {
1.76      ng       1559:     pDoc = pWin.document;
1.465     albertel 1560:     pDoc.write("<\\/table>");
                   1561:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1562:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1563:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1564:     pDoc.write("<\\/form>");
1.351     albertel 1565:     pDoc.write('$end_page_msg_central');
1.128     ng       1566:     pDoc.close();
1.44      ng       1567: }
                   1568: 
                   1569: //====================== Script for keyword highlight options ==============
                   1570:   function kwhighlight() {
                   1571:     var kwclr    = document.SCORE.kwclr.value;
                   1572:     var kwsize   = document.SCORE.kwsize.value;
                   1573:     var kwstyle  = document.SCORE.kwstyle.value;
                   1574:     var redsel = "";
                   1575:     var grnsel = "";
                   1576:     var blusel = "";
                   1577:     if (kwclr=="red")   {var redsel="checked"};
                   1578:     if (kwclr=="green") {var grnsel="checked"};
                   1579:     if (kwclr=="blue")  {var blusel="checked"};
                   1580:     var sznsel = "";
                   1581:     var sz1sel = "";
                   1582:     var sz2sel = "";
                   1583:     if (kwsize=="0")  {var sznsel="checked"};
                   1584:     if (kwsize=="+1") {var sz1sel="checked"};
                   1585:     if (kwsize=="+2") {var sz2sel="checked"};
                   1586:     var synsel = "";
                   1587:     var syisel = "";
                   1588:     var sybsel = "";
                   1589:     if (kwstyle=="")    {var synsel="checked"};
                   1590:     if (kwstyle=="<i>") {var syisel="checked"};
                   1591:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1592:     highlightCentral();
                   1593:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1594:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1595:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1596:     highlightend();
                   1597:     return;
                   1598:   }
                   1599: 
                   1600:   function highlightCentral() {
1.76      ng       1601: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1602:     var xpos = (screen.width-400)/2;
                   1603:     xpos = (xpos < 0) ? '0' : xpos;
                   1604:     var ypos = (screen.height-330)/2-30;
                   1605:     ypos = (ypos < 0) ? '0' : ypos;
                   1606: 
1.206     albertel 1607:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1608:     hwdWin.focus();
                   1609:     var hDoc = hwdWin.document;
1.219     www      1610:     hDoc.$docopen;
1.351     albertel 1611:     hDoc.write('$start_page_highlight_central');
1.76      ng       1612:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1613:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1614: 
                   1615:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1616:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1617:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1618:   }
                   1619: 
                   1620:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1621:     var hDoc = hwdWin.document;
                   1622:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1623:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1624:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1625:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1626:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1627:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1628:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1629:     hDoc.write("<\\/tr>");
1.44      ng       1630:   }
                   1631: 
                   1632:   function highlightend() { 
1.76      ng       1633:     var hDoc = hwdWin.document;
1.465     albertel 1634:     hDoc.write("<\\/table>");
                   1635:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1636:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1637:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1638:     hDoc.write("<\\/form>");
1.351     albertel 1639:     hDoc.write('$end_page_highlight_central');
1.128     ng       1640:     hDoc.close();
1.44      ng       1641:   }
                   1642: 
                   1643: </script>
                   1644: SUBJAVASCRIPT
                   1645: }
                   1646: 
1.349     albertel 1647: sub get_increment {
1.348     bowersj2 1648:     my $increment = $env{'form.increment'};
                   1649:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1650:         $increment != .1) {
                   1651:         $increment = 1;
                   1652:     }
                   1653:     return $increment;
                   1654: }
                   1655: 
1.71      ng       1656: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1657: sub gradeBox {
1.322     albertel 1658:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1659:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1660: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1661:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1662:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1663:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1664:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1665:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1666: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1667:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1668:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1669:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1670: 				       [$partid]);
                   1671:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1672:     if ($last_resets{$partid}) {
                   1673:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1674:     }
1.485     albertel 1675:     $result.='<table border="0"><tr>';
1.71      ng       1676:     my $ctr = 0;
1.348     bowersj2 1677:     my $thisweight = 0;
1.349     albertel 1678:     my $increment = &get_increment();
1.485     albertel 1679: 
                   1680:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1681:     while ($thisweight<=$wgt) {
1.528.2.1  raeburn  1682: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1683: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1684: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1685: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1686: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1687:         $thisweight += $increment;
1.71      ng       1688: 	$ctr++;
                   1689:     }
1.485     albertel 1690:     $radio.='</tr></table>';
                   1691: 
                   1692:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1693: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1694: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1695: 	$wgt.')" /></td>'."\n";
1.485     albertel 1696:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1697: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.528.2.11  raeburn  1698: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
1.485     albertel 1699:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1700: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1701:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1702: 	$line.='<option></option>'.
                   1703: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1704:     } else {
1.485     albertel 1705: 	$line.='<option selected="selected"></option>'.
                   1706: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1707:     }
1.485     albertel 1708:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1709: 
                   1710: 
                   1711:     $result .= 
1.528.2.11  raeburn  1712:             '<td><b>'.&mt('Part').':</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points').':</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.485     albertel 1713:     
                   1714:     $result.='</tr></table>'."\n";
1.71      ng       1715:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1716: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1717: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1718: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1719:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1720:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1721:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1722:         $aggtries.'" />'."\n";
1.323     banghart 1723:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1724:     return $result;
                   1725: }
1.322     albertel 1726: 
                   1727: sub handback_box {
1.323     banghart 1728:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1729:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1730:     my (@respids);
1.375     albertel 1731:      my @part_response_id = &flatten_responseType($responseType);
                   1732:     foreach my $part_response_id (@part_response_id) {
                   1733:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1734:         if ($part eq $partid) {
1.375     albertel 1735:             push(@respids,$resp);
1.323     banghart 1736:         }
                   1737:     }
1.318     banghart 1738:     my $result;
1.323     banghart 1739:     foreach my $respid (@respids) {
1.322     albertel 1740: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1741: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1742: 	next if (!@$files);
                   1743: 	my $file_counter = 1;
1.313     banghart 1744: 	foreach my $file (@$files) {
1.368     banghart 1745: 	    if ($file =~ /\/portfolio\//) {
                   1746:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1747:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1748:     	        $file_disp = "$name.$ext";
                   1749:     	        $file = $file_path.$file_disp;
                   1750:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1751:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1752:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1753:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1754:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1755:     	        $file_counter++;
                   1756: 	    }
1.322     albertel 1757: 	}
1.313     banghart 1758:     }
1.318     banghart 1759:     return $result;    
1.71      ng       1760: }
1.44      ng       1761: 
1.58      albertel 1762: sub show_problem {
1.382     albertel 1763:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1764:     my $rendered;
1.382     albertel 1765:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1766:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1767:     if ($mode eq 'both' or $mode eq 'text') {
                   1768: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1769: 						       $env{'request.course.id'},
                   1770: 						       undef,\%form);
1.144     albertel 1771:     }
1.58      albertel 1772:     if ($removeform) {
                   1773: 	$rendered=~s|<form(.*?)>||g;
                   1774: 	$rendered=~s|</form>||g;
1.374     albertel 1775: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1776:     }
1.144     albertel 1777:     my $companswer;
                   1778:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1779: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1780: 	$companswer=
                   1781: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1782: 						    $env{'request.course.id'},
                   1783: 						    %form);
1.144     albertel 1784:     }
1.58      albertel 1785:     if ($removeform) {
                   1786: 	$companswer=~s|<form(.*?)>||g;
                   1787: 	$companswer=~s|</form>||g;
1.144     albertel 1788: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1789:     }
1.468     albertel 1790:     $rendered=
                   1791: 	'<div class="LC_grade_show_problem_header">'.
                   1792: 	&mt('View of the problem').
                   1793: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1794: 	$rendered.
                   1795: 	'</div>';
                   1796:     $companswer=
                   1797: 	'<div class="LC_grade_show_problem_header">'.
                   1798: 	&mt('Correct answer').
                   1799: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1800: 	$companswer.
                   1801: 	'</div>';
                   1802:     my $result;
1.144     albertel 1803:     if ($mode eq 'both') {
1.468     albertel 1804: 	$result=$rendered.$companswer;
1.144     albertel 1805:     } elsif ($mode eq 'text') {
1.468     albertel 1806: 	$result=$rendered;
1.144     albertel 1807:     } elsif ($mode eq 'answer') {
1.468     albertel 1808: 	$result=$companswer;
1.144     albertel 1809:     }
1.468     albertel 1810:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1811:     return $result;
1.58      albertel 1812: }
1.397     albertel 1813: 
1.396     banghart 1814: sub files_exist {
                   1815:     my ($r, $symb) = @_;
                   1816:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1817: 
1.396     banghart 1818:     foreach my $student (@students) {
                   1819:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1820:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1821: 					      $udom,$uname);
1.396     banghart 1822:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1823:         foreach my $submission (@$string) {
                   1824:             my ($partid,$respid) =
                   1825: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1826:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1827: 					   \%record);
                   1828:             return 1 if (@$files);
1.396     banghart 1829:         }
                   1830:     }
1.397     albertel 1831:     return 0;
1.396     banghart 1832: }
1.397     albertel 1833: 
1.394     banghart 1834: sub download_all_link {
                   1835:     my ($r,$symb) = @_;
1.395     albertel 1836:     my $all_students = 
                   1837: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1838: 
                   1839:     my $parts =
                   1840: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1841: 
1.394     banghart 1842:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1843:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1844:                              'cgi.'.$identifier.'.symb' => $symb,
                   1845:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1846:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1847: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1848:     return
                   1849: }
1.395     albertel 1850: 
1.432     banghart 1851: sub build_section_inputs {
                   1852:     my $section_inputs;
                   1853:     if ($env{'form.section'} eq '') {
                   1854:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1855:     } else {
                   1856:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1857:         foreach my $section (@sections) {
1.432     banghart 1858:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1859:         }
                   1860:     }
                   1861:     return $section_inputs;
                   1862: }
                   1863: 
1.44      ng       1864: # --------------------------- show submissions of a student, option to grade 
                   1865: sub submission {
                   1866:     my ($request,$counter,$total) = @_;
1.257     albertel 1867:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1868:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1869:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1870:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1871:     my $symb = &get_symb($request); 
                   1872:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1873: 
                   1874:     if (!&canview($usec)) {
1.398     albertel 1875: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1876: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1877: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1878: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1879: 	return;
                   1880:     }
                   1881: 
1.257     albertel 1882:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1883:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1884:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1885:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1886:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1887: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1888: 	'/check.gif" height="16" border="0" />';
1.41      ng       1889: 
1.426     albertel 1890:     my %old_essays;
1.41      ng       1891:     # header info
                   1892:     if ($counter == 0) {
                   1893: 	&sub_page_js($request);
1.257     albertel 1894: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1895: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1896: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1897: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1898: 	    &download_all_link($request, $symb);
                   1899: 	}
1.485     albertel 1900: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1901: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1902: 
1.44      ng       1903: 	# option to display problem, only once else it cause problems 
                   1904:         # with the form later since the problem has a form.
1.257     albertel 1905: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1906: 	    my $mode;
1.257     albertel 1907: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1908: 		$mode='both';
1.257     albertel 1909: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1910: 		$mode='text';
1.257     albertel 1911: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1912: 		$mode='answer';
                   1913: 	    }
1.329     albertel 1914: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1915: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1916: 	}
1.441     www      1917: 
1.44      ng       1918: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1919:         # if this subroutine has been called once.
1.41      ng       1920: 	my %keyhash = ();
1.257     albertel 1921: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1922: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1923: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1924: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1925: 
1.257     albertel 1926: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1927: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1928: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1929: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1930: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1931: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1932: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1933: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1934: 	}
1.257     albertel 1935: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1936: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1937: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1938: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1939: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1940: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1941: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1942: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1943: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1944: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1945: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1946: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1947: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1948: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1949: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1950: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1951: 			&build_section_inputs().
1.326     albertel 1952: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1953: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1954: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1955: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1956: 	if ($env{'form.handgrade'} eq 'yes') {
                   1957: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1958: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1959: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1960: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1961: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1962: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1963: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1964: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1965: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1966: 	    }
1.123     ng       1967: 	}
1.41      ng       1968: 	
                   1969: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1970: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1971: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1972: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1973: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1974: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1975: 		'" />'."\n".
                   1976: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1977: 	    $cts++;
                   1978: 	}
                   1979: 	$request->print($prnmsg);
1.32      ng       1980: 
1.257     albertel 1981: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1982: #
                   1983: # Print out the keyword options line
                   1984: #
1.41      ng       1985: 	    $request->print(<<KEYWORDS);
1.38      ng       1986: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1987: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1988: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1989:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1990: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1991: KEYWORDS
1.88      www      1992: #
                   1993: # Load the other essays for similarity check
                   1994: #
1.324     albertel 1995:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1996: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1997: 	    $apath=&escape($apath);
1.88      www      1998: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1999: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2000:         }
                   2001:     }
1.44      ng       2002: 
1.441     www      2003: # This is where output for one specific student would start
1.468     albertel 2004:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2005:     $request->print("\n\n".
1.468     albertel 2006:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2007: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2008: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2009: 
1.257     albertel 2010:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2011: 	my $mode;
1.257     albertel 2012: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2013: 	    $mode='both';
1.257     albertel 2014: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2015: 	    $mode='text';
1.257     albertel 2016: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2017: 	    $mode='answer';
                   2018: 	}
1.329     albertel 2019: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2020: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2021:     }
1.144     albertel 2022: 
1.257     albertel 2023:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2024:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2025: 
1.44      ng       2026:     # Display student info
1.41      ng       2027:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2028:     my $result='<div class="LC_grade_submissions">';
                   2029:     
                   2030:     $result.='<div class="LC_grade_submissions_header">';
                   2031:     $result.= &mt('Submissions');
1.45      ng       2032:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2033: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2034:     if ($env{'form.handgrade'} eq 'no') {
                   2035: 	$result.='<span class="LC_grade_check_note">'.
                   2036: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2037: 
                   2038:     }
                   2039: 
                   2040: 
1.41      ng       2041: 
1.118     ng       2042:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2043:     my $fullname;
                   2044:     my $col_fullnames = [];
1.257     albertel 2045:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2046: 	(my $sub_result,$fullname,$col_fullnames)=
                   2047: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2048: 				 $counter);
                   2049: 	$result.=$sub_result;
1.41      ng       2050:     }
1.44      ng       2051:     $request->print($result."\n");
1.468     albertel 2052:     $request->print('</div>'."\n");
1.44      ng       2053:     # print student answer/submission
                   2054:     # Options are (1) Handgaded submission only
                   2055:     #             (2) Last submission, includes submission that is not handgraded 
                   2056:     #                  (for multi-response type part)
                   2057:     #             (3) Last submission plus the parts info
                   2058:     #             (4) The whole record for this student
1.257     albertel 2059:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2060: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2061: 	
                   2062: 	my $lastsubonly;
                   2063: 
1.151     albertel 2064: 	if ($$timestamp eq '') {
1.468     albertel 2065: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2066: 	} else {
1.468     albertel 2067: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2068: 
1.151     albertel 2069: 	    my %seenparts;
1.375     albertel 2070: 	    my @part_response_id = &flatten_responseType($responseType);
                   2071: 	    foreach my $part (@part_response_id) {
1.393     albertel 2072: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2073: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2074: 
1.375     albertel 2075: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2076: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2077: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2078: 		    if (exists($seenparts{$partid})) { next; }
                   2079: 		    $seenparts{$partid}=1;
1.207     albertel 2080: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2081: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2082: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2083: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2084: 			'\');" target="_self">'.
1.257     albertel 2085: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2086: 		    $request->print($submitby);
                   2087: 		    next;
                   2088: 		}
                   2089: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2090: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2091: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2092: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2093: 			' )</span>&nbsp; &nbsp;'.
1.528.2.11  raeburn  2094: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2095: 		    next;
                   2096: 		}
1.468     albertel 2097: 		foreach my $submission (@$string) {
                   2098: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2099: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2100: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2101: 		    # Similarity check
                   2102: 		    my $similar='';
1.257     albertel 2103: 		    if($env{'form.checkPlag'}){
1.151     albertel 2104: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2105: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2106: 			if ($osim) {
                   2107: 			    $osim=int($osim*100.0);
1.426     albertel 2108: 			    my %old_course_desc = 
                   2109: 				&Apache::lonnet::coursedescription($ocrsid,
                   2110: 								   {'one_time' => 1});
                   2111: 
                   2112: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2113: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2114: 				    $osim,
                   2115: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2116: 				    $oname,$odom,
1.426     albertel 2117: 				    $old_course_desc{'description'},
1.427     albertel 2118: 				    $old_course_desc{'num'},
1.426     albertel 2119: 				    $old_course_desc{'domain'}).
1.398     albertel 2120: 				'</span></h3><blockquote><i>'.
1.151     albertel 2121: 				&keywords_highlight($oessay).
                   2122: 				'</i></blockquote><hr />';
                   2123: 			}
1.150     albertel 2124: 		    }
1.151     albertel 2125: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2126: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2127: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2128: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2129: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2130: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2131: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2132: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2133: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2134: 			if (@$files) {
1.528.2.7  raeburn  2135: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
1.303     banghart 2136: 			    my $file_counter = 0;
1.313     banghart 2137: 			    foreach my $file (@$files) {
1.468     albertel 2138: 			        $file_counter++;
1.232     albertel 2139: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2140: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2141: 			    }
1.236     albertel 2142: 			    $lastsubonly.='<br />';
1.41      ng       2143: 			}
1.468     albertel 2144: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2145: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
1.528.2.11  raeburn  2146: 					 $respid,\%record,$order,undef,$uname,$udom);
1.151     albertel 2147: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2148: 			$lastsubonly.='</div>';
1.41      ng       2149: 		    }
                   2150: 		}
                   2151: 	    }
1.468     albertel 2152: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2153: 	}
                   2154: 	$request->print($lastsubonly);
1.468     albertel 2155:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2156: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2157: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2158:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2159: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2160: 								 $env{'request.course.id'},
1.44      ng       2161: 								 $last,'.submission',
                   2162: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2163:     }
1.120     ng       2164: 
1.121     ng       2165:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2166: 	.$udom.'" />'."\n");
1.44      ng       2167:     # return if view submission with no grading option
1.257     albertel 2168:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2169: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2170: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2171: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2172: 	$toGrade.='</div>'."\n";
1.257     albertel 2173: 	if (($env{'form.command'} eq 'submission') || 
                   2174: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2175: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2176: 	}
1.180     albertel 2177: 	$request->print($toGrade);
1.41      ng       2178: 	return;
1.180     albertel 2179:     } else {
1.468     albertel 2180: 	$request->print('</div>'."\n");
1.41      ng       2181:     }
1.33      ng       2182: 
1.121     ng       2183:     # essay grading message center
1.257     albertel 2184:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2185: 	my $result='<div class="LC_grade_message_center">';
                   2186:     
                   2187: 	$result.='<div class="LC_grade_message_center_header">'.
                   2188: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2189: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2190: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2191: 	if (scalar(@$col_fullnames) > 0) {
                   2192: 	    my $lastone = pop(@$col_fullnames);
                   2193: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2194: 	}
                   2195: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2196: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2197: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2198: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2199: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2200: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2201: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2202: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2203: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2204: 	    '<br />&nbsp;('.
1.468     albertel 2205: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2206: 	$result.='</div></div>';
1.121     ng       2207: 	$request->print($result);
1.118     ng       2208:     }
1.41      ng       2209: 
                   2210:     my %seen = ();
                   2211:     my @partlist;
1.129     ng       2212:     my @gradePartRespid;
1.375     albertel 2213:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2214:     $request->print('<div class="LC_grade_assign">'.
                   2215: 		    
                   2216: 		    '<div class="LC_grade_assign_header">'.
                   2217: 		    &mt('Assign Grades').'</div>'.
                   2218: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2219:     foreach my $part_response_id (@part_response_id) {
                   2220:     	my ($partid,$respid) = @{ $part_response_id };
                   2221: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2222: 	next if ($seen{$partid} > 0);
1.41      ng       2223: 	$seen{$partid}++;
1.393     albertel 2224: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2225: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2226: 	push(@partlist,$partid);
                   2227: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2228: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2229:     }
1.468     albertel 2230:     $request->print('</div></div>');
                   2231: 
                   2232:     $request->print('<div class="LC_grade_info_links">');
                   2233:     if ($perm{'vgr'}) {
                   2234: 	$request->print(
                   2235: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2236: 						   $uname,$udom,'check'));
                   2237:     }
                   2238:     if ($perm{'opa'}) {
                   2239: 	$request->print(
                   2240: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2241: 					 $uname,$udom,$symb,'check'));
                   2242:     }
                   2243:     $request->print('</div>');
                   2244: 
1.45      ng       2245:     $result='<input type="hidden" name="partlist'.$counter.
                   2246: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2247:     $result.='<input type="hidden" name="gradePartRespid'.
                   2248: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2249:     my $ctr = 0;
                   2250:     while ($ctr < scalar(@partlist)) {
                   2251: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2252: 	    $partlist[$ctr].'" />'."\n";
                   2253: 	$ctr++;
                   2254:     }
1.468     albertel 2255:     $request->print($result.''."\n");
1.41      ng       2256: 
1.441     www      2257: # Done with printing info for one student
                   2258: 
1.468     albertel 2259:     $request->print('</div>');#LC_grade_show_user_body
                   2260:     $request->print('</div>');#LC_grade_show_user
1.441     www      2261: 
                   2262: 
1.41      ng       2263:     # print end of form
                   2264:     if ($counter == $total) {
1.297     www      2265: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2266: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2267: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2268: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2269: 	my $ntstu ='<select name="NTSTU">'.
                   2270: 	    '<option>1</option><option>2</option>'.
                   2271: 	    '<option>3</option><option>5</option>'.
                   2272: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2273: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2274: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.528.2.11  raeburn  2275: 	$endform.=&mt('[quant,_1,student]',$ntstu);
1.485     albertel 2276: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2277: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2278: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2279: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2280: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2281:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2282:             "' name='increment' />";
1.485     albertel 2283: 	$endform.='</td></tr></table></form>';
1.324     albertel 2284: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2285: 	$request->print($endform);
                   2286:     }
                   2287:     return '';
1.38      ng       2288: }
                   2289: 
1.464     albertel 2290: sub check_collaborators {
                   2291:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2292:     my ($result,@col_fullnames);
                   2293:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2294:     foreach my $part (keys(%$handgrade)) {
                   2295: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2296: 					'.maxcollaborators',
                   2297: 					$symb,$udom,$uname);
                   2298: 	next if ($ncol <= 0);
                   2299: 	$part =~ s/\_/\./g;
                   2300: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2301: 	my (@good_collaborators, @bad_collaborators);
                   2302: 	foreach my $possible_collaborator
                   2303: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2304: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2305: 	    next if ($possible_collaborator eq '');
                   2306: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2307: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2308: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2309: 	    # Doing this grep allows 'fuzzy' specification
                   2310: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2311: 			       keys(%$classlist));
                   2312: 	    if (! scalar(@matches)) {
                   2313: 		push(@bad_collaborators, $possible_collaborator);
                   2314: 	    } else {
                   2315: 		push(@good_collaborators, @matches);
                   2316: 	    }
                   2317: 	}
                   2318: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2319: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2320: 	    foreach my $name (@good_collaborators) {
                   2321: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2322: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2323: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2324: 	    }
                   2325: 	    $result.='<br />'."\n";
1.466     albertel 2326: 	    my ($part)=split(/\./,$part);
1.464     albertel 2327: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2328: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2329: 		"\n";
                   2330: 	}
                   2331: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2332: 	    $result.='<div class="LC_warning">';
1.464     albertel 2333: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2334: 	    $result .= '</div>';
                   2335: 	}         
                   2336: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2337: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2338: 	    $result .= &mt('This student has submitted too many '.
                   2339: 		'collaborators.  Maximum is [_1].',$ncol);
                   2340: 	    $result .= '</div>';
                   2341: 	}
                   2342:     }
                   2343:     return ($result,$fullname,\@col_fullnames);
                   2344: }
                   2345: 
1.44      ng       2346: #--- Retrieve the last submission for all the parts
1.38      ng       2347: sub get_last_submission {
1.119     ng       2348:     my ($returnhash)=@_;
1.46      ng       2349:     my (@string,$timestamp);
1.119     ng       2350:     if ($$returnhash{'version'}) {
1.46      ng       2351: 	my %lasthash=();
                   2352: 	my ($version);
1.119     ng       2353: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2354: 	    foreach my $key (sort(split(/\:/,
                   2355: 					$$returnhash{$version.':keys'}))) {
                   2356: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2357: 		$timestamp = 
1.528.2.6  raeburn  2358: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2359: 	    }
                   2360: 	}
1.397     albertel 2361: 	foreach my $key (keys(%lasthash)) {
                   2362: 	    next if ($key !~ /\.submission$/);
                   2363: 
                   2364: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2365: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2366: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2367: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2368: 	}
                   2369:     }
1.397     albertel 2370:     if (!@string) {
                   2371: 	$string[0] =
1.398     albertel 2372: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2373:     }
                   2374:     return (\@string,\$timestamp);
1.38      ng       2375: }
1.35      ng       2376: 
1.44      ng       2377: #--- High light keywords, with style choosen by user.
1.38      ng       2378: sub keywords_highlight {
1.44      ng       2379:     my $string    = shift;
1.257     albertel 2380:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2381:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2382:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2383:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2384:     foreach my $keyword (@keylist) {
                   2385: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2386:     }
                   2387:     return $string;
1.38      ng       2388: }
1.36      ng       2389: 
1.44      ng       2390: #--- Called from submission routine
1.38      ng       2391: sub processHandGrade {
1.41      ng       2392:     my ($request) = shift;
1.324     albertel 2393:     my $symb   = &get_symb($request);
                   2394:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2395:     my $button = $env{'form.gradeOpt'};
                   2396:     my $ngrade = $env{'form.NCT'};
                   2397:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2398:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2399:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2400: 
1.44      ng       2401:     if ($button eq 'Save & Next') {
                   2402: 	my $ctr = 0;
                   2403: 	while ($ctr < $ngrade) {
1.257     albertel 2404: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2405: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2406: 	    if ($errorflag eq 'no_score') {
                   2407: 		$ctr++;
                   2408: 		next;
                   2409: 	    }
1.104     albertel 2410: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2411: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2412: 		$ctr++;
                   2413: 		next;
                   2414: 	    }
1.257     albertel 2415: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2416: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2417: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2418:             my ($feedurl,$showsymb) =
                   2419: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2420: 	    my $messagetail;
1.62      albertel 2421: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2422: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2423: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2424: 		$subject.=' ['.$restitle.']';
1.44      ng       2425: 		my (@msgnum) = split(/,/,$includemsg);
                   2426: 		foreach (@msgnum) {
1.257     albertel 2427: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2428: 		}
1.80      ng       2429: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2430: 		if ($env{'form.withgrades'.$ctr}) {
                   2431: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2432: 		    $messagetail = " for <a href=\"".
1.418     albertel 2433: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2434: 		}
                   2435: 		$msgstatus = 
                   2436:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2437: 						     $message.$messagetail,
1.418     albertel 2438:                                                      undef,$feedurl,undef,
1.386     raeburn  2439:                                                      undef,undef,$showsymb,
                   2440:                                                      $restitle);
                   2441: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2442: 				$msgstatus);
1.44      ng       2443: 	    }
1.257     albertel 2444: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2445: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2446: 		foreach my $collabstr (@collabstrs) {
                   2447: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2448: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2449: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2450: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2451: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2452: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2453: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2454: 			    next;
1.418     albertel 2455: 			} elsif ($message ne '') {
                   2456: 			    my ($baseurl,$showsymb) = 
                   2457: 				&get_feedurl_and_symb($symb,$collaborator,
                   2458: 						      $udom);
                   2459: 			    if ($env{'form.withgrades'.$ctr}) {
                   2460: 				$messagetail = " for <a href=\"".
1.386     raeburn  2461:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2462: 			    }
1.418     albertel 2463: 			    $msgstatus = 
                   2464: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2465: 			}
1.44      ng       2466: 		    }
                   2467: 		}
                   2468: 	    }
                   2469: 	    $ctr++;
                   2470: 	}
                   2471:     }
                   2472: 
1.257     albertel 2473:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2474: 	# Keywords sorted in alphabatical order
1.257     albertel 2475: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2476: 	my %keyhash = ();
1.257     albertel 2477: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2478: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2479: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2480: 	$env{'form.keywords'} = join(' ',@keywords);
                   2481: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2482: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2483: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2484: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2485: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2486: 
                   2487: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2488: 	# New messages are saved in env for the next student.
1.119     ng       2489: 	# All messages are saved in nohist_handgrade.db
                   2490: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2491: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2492: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2493: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2494: 		$idx++;
                   2495: 	    }
                   2496: 	    $ctr++;
1.41      ng       2497: 	}
1.119     ng       2498: 	$ctr = 0;
                   2499: 	while ($ctr < $ngrade) {
1.257     albertel 2500: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2501: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2502: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2503: 		$idx++;
                   2504: 	    }
                   2505: 	    $ctr++;
1.41      ng       2506: 	}
1.257     albertel 2507: 	$env{'form.savemsgN'} = --$idx;
                   2508: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2509: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2510: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2511:     }
1.44      ng       2512:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2513:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2514:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2515: 	my ($ctr,$total) = (0,0);
                   2516: 	while ($ctr < $ngrade) {
1.257     albertel 2517: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2518: 	    $ctr++;
                   2519: 	}
1.257     albertel 2520: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2521: 	$ctr = 0;
                   2522: 	while ($ctr < $total) {
1.257     albertel 2523: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2524: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2525: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2526: 	    &submission($request,$ctr,$total-1);
1.41      ng       2527: 	    $ctr++;
                   2528: 	}
                   2529: 	return '';
                   2530:     }
1.36      ng       2531: 
1.121     ng       2532: # Go directly to grade student - from submission or link from chart page
1.120     ng       2533:     if ($button eq 'Grade Student') {
1.324     albertel 2534: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2535: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2536: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2537: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2538: 	&submission($request,0,0);
                   2539: 	return '';
                   2540:     }
                   2541: 
1.44      ng       2542:     # Get the next/previous one or group of students
1.257     albertel 2543:     my $firststu = $env{'form.unamedom0'};
                   2544:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2545:     my $ctr = 2;
1.41      ng       2546:     while ($laststu eq '') {
1.257     albertel 2547: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2548: 	$ctr++;
                   2549: 	$laststu = $firststu if ($ctr > $ngrade);
                   2550:     }
1.44      ng       2551: 
1.41      ng       2552:     my (@parsedlist,@nextlist);
                   2553:     my ($nextflg) = 0;
1.524     raeburn  2554:     foreach my $item (sort 
1.294     albertel 2555: 	     {
                   2556: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2557: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2558: 		 }
                   2559: 		 return $a cmp $b;
                   2560: 	     } (keys(%$fullname))) {
1.41      ng       2561: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2562: 	    push(@parsedlist,$item);
1.41      ng       2563: 	}
1.524     raeburn  2564: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2565: 	if ($button eq 'Previous') {
1.524     raeburn  2566: 	    last if ($item eq $firststu);
                   2567: 	    push(@parsedlist,$item);
1.41      ng       2568: 	}
                   2569:     }
                   2570:     $ctr = 0;
                   2571:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2572:     my ($partlist) = &response_type($symb);
1.41      ng       2573:     foreach my $student (@parsedlist) {
1.257     albertel 2574: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2575: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2576: 	
                   2577: 	if ($submitonly eq 'queued') {
                   2578: 	    my %queue_status = 
                   2579: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2580: 							$udom,$uname);
                   2581: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2582: 	}
                   2583: 
1.156     albertel 2584: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2585: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2586: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2587: 	    my $submitted = 0;
1.248     albertel 2588: 	    my $ungraded = 0;
                   2589: 	    my $incorrect = 0;
1.524     raeburn  2590: 	    foreach my $item (keys(%status)) {
                   2591: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2592: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2593: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2594: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2595: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2596: 		    $submitted = 0;
                   2597: 		}
1.41      ng       2598: 	    }
1.156     albertel 2599: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2600: 				     $submitonly eq 'incorrect' ||
                   2601: 				     $submitonly eq 'graded'));
1.248     albertel 2602: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2603: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2604: 	}
1.524     raeburn  2605: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2606: 	last if ($ctr == $ntstu);
1.41      ng       2607: 	$ctr++;
                   2608:     }
1.36      ng       2609: 
1.41      ng       2610:     $ctr = 0;
                   2611:     my $total = scalar(@nextlist)-1;
1.39      ng       2612: 
1.524     raeburn  2613:     foreach (sort(@nextlist)) {
1.41      ng       2614: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2615: 	$env{'form.student'}  = $uname;
                   2616: 	$env{'form.userdom'}  = $udom;
                   2617: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2618: 	&submission($request,$ctr,$total);
                   2619: 	$ctr++;
                   2620:     }
                   2621:     if ($total < 0) {
1.485     albertel 2622: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2623: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2624: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2625: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2626: 	$request->print($the_end);
                   2627:     }
                   2628:     return '';
1.38      ng       2629: }
1.36      ng       2630: 
1.44      ng       2631: #---- Save the score and award for each student, if changed
1.38      ng       2632: sub saveHandGrade {
1.324     albertel 2633:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2634:     my @version_parts;
1.104     albertel 2635:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2636: 					   $env{'request.course.id'});
1.104     albertel 2637:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2638:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2639:     my @parts_graded;
1.77      ng       2640:     my %newrecord  = ();
                   2641:     my ($pts,$wgt) = ('','');
1.269     raeburn  2642:     my %aggregate = ();
                   2643:     my $aggregateflag = 0;
1.301     albertel 2644:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2645:     foreach my $new_part (@parts) {
1.337     banghart 2646: 	#collaborator ($submi may vary for different parts
1.259     banghart 2647: 	if ($submitter && $new_part ne $part) { next; }
                   2648: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2649: 	if ($dropMenu eq 'excused') {
1.259     banghart 2650: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2651: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2652: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2653: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2654: 		}
1.364     banghart 2655: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2656: 	    }
1.125     ng       2657: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2658: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2659: 	    foreach my $key (keys(%record)) {
1.259     banghart 2660: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2661: 	    }
1.259     banghart 2662: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2663: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2664:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2665: 
                   2666:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2667: 					       [$new_part]);
                   2668:             my $aggtries =$totaltries;
1.269     raeburn  2669:             if ($last_resets{$new_part}) {
1.270     albertel 2670:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2671: 					   $new_part);
1.269     raeburn  2672:             }
1.270     albertel 2673: 
                   2674:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2675:             if ($aggtries > 0) {
1.327     albertel 2676:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2677:                 $aggregateflag = 1;
                   2678:             }
1.125     ng       2679: 	} elsif ($dropMenu eq '') {
1.259     banghart 2680: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2681: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2682: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2683: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2684: 		next;
                   2685: 	    }
1.259     banghart 2686: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2687: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2688: 	    my $partial= $pts/$wgt;
1.259     banghart 2689: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2690: 		#do not update score for part if not changed.
1.346     banghart 2691:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2692: 		next;
1.251     banghart 2693: 	    } else {
1.524     raeburn  2694: 	        push(@parts_graded,$new_part);
1.153     albertel 2695: 	    }
1.259     banghart 2696: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2697: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2698: 	    }
1.259     banghart 2699: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2700: 	    if ($partial == 0) {
1.153     albertel 2701: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2702: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2703: 		}
1.41      ng       2704: 	    } else {
1.153     albertel 2705: 		if ($record{$reckey} ne 'correct_by_override') {
                   2706: 		    $newrecord{$reckey} = 'correct_by_override';
                   2707: 		}
                   2708: 	    }	    
                   2709: 	    if ($submitter && 
1.259     banghart 2710: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2711: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2712: 	    }
1.259     banghart 2713: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2714: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2715: 	}
1.259     banghart 2716: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2717: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2718: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2719: 	        $dropMenu eq 'reset status')
                   2720: 	   {
1.524     raeburn  2721: 	    push(@version_parts,$new_part);
1.259     banghart 2722: 	}
1.41      ng       2723:     }
1.301     albertel 2724:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2725:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2726: 
1.344     albertel 2727:     if (%newrecord) {
                   2728:         if (@version_parts) {
1.364     banghart 2729:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2730:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2731: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2732: 	    foreach my $new_part (@version_parts) {
                   2733: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2734: 				$new_part,\%newrecord);
                   2735: 	    }
1.259     banghart 2736:         }
1.44      ng       2737: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2738: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2739: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2740: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2741:     }
1.269     raeburn  2742:     if ($aggregateflag) {
                   2743:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2744: 			      $cdom,$cnum);
1.269     raeburn  2745:     }
1.301     albertel 2746:     return ('',$pts,$wgt);
1.36      ng       2747: }
1.322     albertel 2748: 
1.380     albertel 2749: sub check_and_remove_from_queue {
                   2750:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2751:     my @ungraded_parts;
                   2752:     foreach my $part (@{$parts}) {
                   2753: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2754: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2755: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2756: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2757: 		) {
                   2758: 	    push(@ungraded_parts, $part);
                   2759: 	}
                   2760:     }
                   2761:     if ( !@ungraded_parts ) {
                   2762: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2763: 					       $cnum,$domain,$stuname);
                   2764:     }
                   2765: }
                   2766: 
1.337     banghart 2767: sub handback_files {
                   2768:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2769:     my $portfolio_root = '/userfiles/portfolio';
1.359     www      2770:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2771: 
                   2772:     my @part_response_id = &flatten_responseType($responseType);
                   2773:     foreach my $part_response_id (@part_response_id) {
                   2774:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2775: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2776:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2777:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2778:                 my $file_counter = 1;
1.367     albertel 2779: 		my $file_msg;
1.337     banghart 2780:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2781:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2782:                     my ($directory,$answer_file) = 
                   2783:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2784:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2785: 		        &file_name_version_ext($answer_file);
1.355     banghart 2786: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2787:                     my $getpropath = 1;
                   2788: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2789: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2790:                     # fix file name
                   2791:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2792:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2793:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2794:             	                                $save_file_name);
1.337     banghart 2795:                     if ($result !~ m|^/uploaded/|) {
1.528.2.2  raeburn  2796:                         $request->print('<br /><span class="LC_error">'.
                   2797:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2798:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2799:                                         '</span>');
1.356     banghart 2800:                     } else {
1.360     banghart 2801:                         # mark the file as read only
                   2802:                         my @files = ($save_file_name);
1.372     albertel 2803:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2804:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2805: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2806: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2807: 			}
                   2808:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2809: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2810: 
1.337     banghart 2811:                     }
                   2812:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2813:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2814:                     $file_counter++;
                   2815:                 }
1.367     albertel 2816: 		my $subject = "File Handed Back by Instructor ";
                   2817: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2818: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2819: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2820: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2821: 		my ($feedurl,$showsymb) = 
                   2822: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2823:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2824: 		my $msgstatus = 
                   2825:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2826: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2827:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2828:             }
                   2829:         }
1.338     banghart 2830:     return;
1.337     banghart 2831: }
                   2832: 
1.418     albertel 2833: sub get_feedurl_and_symb {
                   2834:     my ($symb,$uname,$udom) = @_;
                   2835:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2836:     $url = &Apache::lonnet::clutter($url);
                   2837:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2838: 					$symb,$udom,$uname);
                   2839:     if ($encrypturl =~ /^yes$/i) {
                   2840: 	&Apache::lonenc::encrypted(\$url,1);
                   2841: 	&Apache::lonenc::encrypted(\$symb,1);
                   2842:     }
                   2843:     return ($url,$symb);
                   2844: }
                   2845: 
1.313     banghart 2846: sub get_submitted_files {
                   2847:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2848:     my @files;
                   2849:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2850:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2851:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2852:     	    push(@files,$file_url.$file);
                   2853:         }
                   2854:     }
                   2855:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2856:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2857:     }
                   2858:     return (\@files);
                   2859: }
1.322     albertel 2860: 
1.269     raeburn  2861: # ----------- Provides number of tries since last reset.
                   2862: sub get_num_tries {
                   2863:     my ($record,$last_reset,$part) = @_;
                   2864:     my $timestamp = '';
                   2865:     my $num_tries = 0;
                   2866:     if ($$record{'version'}) {
                   2867:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2868:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2869:                 $timestamp = $$record{$version.':timestamp'};
                   2870:                 if ($timestamp > $last_reset) {
                   2871:                     $num_tries ++;
                   2872:                 } else {
                   2873:                     last;
                   2874:                 }
                   2875:             }
                   2876:         }
                   2877:     }
                   2878:     return $num_tries;
                   2879: }
                   2880: 
                   2881: # ----------- Determine decrements required in aggregate totals 
                   2882: sub decrement_aggs {
                   2883:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2884:     my %decrement = (
                   2885:                         attempts => 0,
                   2886:                         users => 0,
                   2887:                         correct => 0
                   2888:                     );
                   2889:     $decrement{'attempts'} = $aggtries;
                   2890:     if ($solvedstatus =~ /^correct/) {
                   2891:         $decrement{'correct'} = 1;
                   2892:     }
                   2893:     if ($aggtries == $totaltries) {
                   2894:         $decrement{'users'} = 1;
                   2895:     }
1.524     raeburn  2896:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2897:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2898:     }
                   2899:     return;
                   2900: }
                   2901: 
                   2902: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2903: sub get_last_resets {
1.270     albertel 2904:     my ($symb,$courseid,$partids) =@_;
                   2905:     my %last_resets;
1.269     raeburn  2906:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2907:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2908:     my @keys;
                   2909:     foreach my $part (@{$partids}) {
                   2910: 	push(@keys,"$symb\0$part\0resettime");
                   2911:     }
                   2912:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2913: 				     $cdom,$cname);
                   2914:     foreach my $part (@{$partids}) {
                   2915: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2916:     }
1.270     albertel 2917:     return %last_resets;
1.269     raeburn  2918: }
                   2919: 
1.251     banghart 2920: # ----------- Handles creating versions for portfolio files as answers
                   2921: sub version_portfiles {
1.343     banghart 2922:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2923:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2924:     my @returned_keys;
1.255     banghart 2925:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2926:     my $portfolio_root = '/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.517     raeburn  2937:                 my $getpropath = 1;    
                   2938:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 2939:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2940:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2941:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2942:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2943:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2944:                         [$directory.$new_answer],
1.306     banghart 2945:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2946:                 }
1.252     banghart 2947:             }
1.343     banghart 2948:             $$record{$key} = join(',',@versioned_portfiles);
                   2949:             push(@returned_keys,$key);
1.251     banghart 2950:         }
                   2951:     } 
1.343     banghart 2952:     return (@returned_keys);   
1.305     banghart 2953: }
                   2954: 
1.307     banghart 2955: sub get_next_version {
1.341     banghart 2956:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2957:     my $version;
                   2958:     foreach my $row (@$dir_list) {
                   2959:         my ($file) = split(/\&/,$row,2);
                   2960:         my ($file_name,$file_version,$file_ext) =
                   2961: 	    &file_name_version_ext($file);
                   2962:         if (($file_name eq $answer_name) && 
                   2963: 	    ($file_ext eq $answer_ext)) {
                   2964:                 # gets here if filename and extension match, regardless of version
                   2965:                 if ($file_version ne '') {
                   2966:                 # a versioned file is found  so save it for later
                   2967:                 if ($file_version > $version) {
                   2968: 		    $version = $file_version;
                   2969: 	        }
                   2970:             }
                   2971:         }
                   2972:     } 
                   2973:     $version ++;
                   2974:     return($version);
                   2975: }
                   2976: 
1.305     banghart 2977: sub version_selected_portfile {
1.306     banghart 2978:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2979:     my ($answer_name,$answer_ver,$answer_ext) =
                   2980:         &file_name_version_ext($file_name);
                   2981:     my $new_answer;
                   2982:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2983:     if($env{'form.copy'} eq '-1') {
                   2984:         $new_answer = 'problem getting file';
                   2985:     } else {
                   2986:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2987:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2988:                             $stu_name,$domain,'copy',
                   2989: 		        '/portfolio'.$directory.$new_answer);
                   2990:     }    
                   2991:     return ($new_answer);
1.251     banghart 2992: }
                   2993: 
1.304     albertel 2994: sub file_name_version_ext {
                   2995:     my ($file)=@_;
                   2996:     my @file_parts = split(/\./, $file);
                   2997:     my ($name,$version,$ext);
                   2998:     if (@file_parts > 1) {
                   2999: 	$ext=pop(@file_parts);
                   3000: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3001: 	    $version=pop(@file_parts);
                   3002: 	}
                   3003: 	$name=join('.',@file_parts);
                   3004:     } else {
                   3005: 	$name=join('.',@file_parts);
                   3006:     }
                   3007:     return($name,$version,$ext);
                   3008: }
                   3009: 
1.44      ng       3010: #--------------------------------------------------------------------------------------
                   3011: #
                   3012: #-------------------------- Next few routines handles grading by section or whole class
                   3013: #
                   3014: #--- Javascript to handle grading by section or whole class
1.42      ng       3015: sub viewgrades_js {
                   3016:     my ($request) = shift;
                   3017: 
1.528.2.11  raeburn  3018:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3019:     $request->print(<<VIEWJAVASCRIPT);
                   3020: <script type="text/javascript" language="javascript">
1.45      ng       3021:    function writePoint(partid,weight,point) {
1.125     ng       3022: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3023: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3024: 	if (point == "textval") {
1.125     ng       3025: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3026: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.528.2.11  raeburn  3027: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3028: 		var resetbox = false;
                   3029: 		for (var i=0; i<radioButton.length; i++) {
                   3030: 		    if (radioButton[i].checked) {
                   3031: 			textbox.value = i;
                   3032: 			resetbox = true;
                   3033: 		    }
                   3034: 		}
                   3035: 		if (!resetbox) {
                   3036: 		    textbox.value = "";
                   3037: 		}
                   3038: 		return;
                   3039: 	    }
1.109     matthew  3040: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3041: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3042: 				   ") greater than the weight for the part. Accept?");
                   3043: 		if (resp == false) {
                   3044: 		    textbox.value = "";
                   3045: 		    return;
                   3046: 		}
                   3047: 	    }
1.42      ng       3048: 	    for (var i=0; i<radioButton.length; i++) {
                   3049: 		radioButton[i].checked=false;
1.109     matthew  3050: 		if (parseFloat(point) == i) {
1.42      ng       3051: 		    radioButton[i].checked=true;
                   3052: 		}
                   3053: 	    }
1.41      ng       3054: 
1.42      ng       3055: 	} else {
1.125     ng       3056: 	    textbox.value = parseFloat(point);
1.42      ng       3057: 	}
1.41      ng       3058: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3059: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3060: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3061: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3062: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3063: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3064: 	    if (saveval != "correct") {
                   3065: 		scorename.value = point;
1.43      ng       3066: 		if (selname[0].selected != true) {
                   3067: 		    selname[0].selected = true;
                   3068: 		}
1.42      ng       3069: 	    }
                   3070: 	}
1.125     ng       3071: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3072:     }
                   3073: 
                   3074:     function writeRadText(partid,weight) {
1.125     ng       3075: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3076: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3077:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3078: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3079: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3080: 	    for (var i=0; i<radioButton.length; i++) {
                   3081: 		radioButton[i].checked=false;
                   3082: 
                   3083: 	    }
                   3084: 	    textbox.value = "";
                   3085: 
                   3086: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3087: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3088: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3089: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3090: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3091: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3092: 		if ((saveval != "correct") || override) {
1.42      ng       3093: 		    scorename.value = "";
1.125     ng       3094: 		    if (selval[1].selected) {
                   3095: 			selname[1].selected = true;
                   3096: 		    } else {
                   3097: 			selname[2].selected = true;
                   3098: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3099: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3100: 		    }
1.42      ng       3101: 		}
                   3102: 	    }
1.43      ng       3103: 	} else {
                   3104: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3105: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3106: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3107: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3108: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3109: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3110: 		if ((saveval != "correct") || override) {
1.125     ng       3111: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3112: 		    selname[0].selected = true;
                   3113: 		}
                   3114: 	    }
                   3115: 	}	    
1.42      ng       3116:     }
                   3117: 
                   3118:     function changeSelect(partid,user) {
1.125     ng       3119: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3120: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3121: 	var point  = textbox.value;
1.125     ng       3122: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3123: 
1.109     matthew  3124: 	if (isNaN(point) || parseFloat(point) < 0) {
1.528.2.11  raeburn  3125: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3126: 	    textbox.value = "";
                   3127: 	    return;
                   3128: 	}
1.109     matthew  3129: 	if (parseFloat(point) > parseFloat(weight)) {
                   3130: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3131: 			       ") greater than the weight of the part. Accept?");
                   3132: 	    if (resp == false) {
                   3133: 		textbox.value = "";
                   3134: 		return;
                   3135: 	    }
                   3136: 	}
1.42      ng       3137: 	selval[0].selected = true;
                   3138:     }
                   3139: 
                   3140:     function changeOneScore(partid,user) {
1.125     ng       3141: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3142: 	if (selval[1].selected || selval[2].selected) {
                   3143: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3144: 	    if (selval[2].selected) {
                   3145: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3146: 	    }
1.269     raeburn  3147:         }
1.42      ng       3148:     }
                   3149: 
                   3150:     function resetEntry(numpart) {
                   3151: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3152: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3153: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3154: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3155: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3156: 	    for (var i=0; i<radioButton.length; i++) {
                   3157: 		radioButton[i].checked=false;
                   3158: 
                   3159: 	    }
                   3160: 	    textbox.value = "";
                   3161: 	    selval[0].selected = true;
                   3162: 
                   3163: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3164: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3165: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3166: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3167: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3168: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3169: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3170: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3171: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3172: 		if (saveselval == "excused") {
1.43      ng       3173: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3174: 		} else {
1.43      ng       3175: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3176: 		}
                   3177: 	    }
1.41      ng       3178: 	}
1.42      ng       3179:     }
                   3180: 
1.41      ng       3181: </script>
                   3182: VIEWJAVASCRIPT
1.42      ng       3183: }
                   3184: 
1.44      ng       3185: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3186: sub viewgrades {
                   3187:     my ($request) = shift;
                   3188:     &viewgrades_js($request);
1.41      ng       3189: 
1.324     albertel 3190:     my ($symb) = &get_symb($request);
1.168     albertel 3191:     #need to make sure we have the correct data for later EXT calls, 
                   3192:     #thus invalidate the cache
                   3193:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3194:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3195:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3196:     &Apache::lonnet::clear_EXT_cache_status();
                   3197: 
1.398     albertel 3198:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3199:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3200: 
                   3201:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3202:     $result.=&jscriptNform($symb);
1.41      ng       3203: 
1.44      ng       3204:     #beginning of class grading form
1.442     banghart 3205:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3206:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3207: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3208: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3209: 	&build_section_inputs().
1.257     albertel 3210: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3211: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3212: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3213: 
1.528.2.11  raeburn  3214:     my ($common_header,$specific_header);
1.257     albertel 3215:     if ($env{'form.section'} eq 'all') {
1.528.2.11  raeburn  3216:         $common_header = &mt('Assign Common Grade to Class');
                   3217:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3218:     } elsif ($env{'form.section'} eq 'none') {
1.528.2.11  raeburn  3219:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3220:         $specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3221:     } else {
1.528.2.11  raeburn  3222:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3223:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3224:         $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3225:     }
1.528.2.11  raeburn  3226:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3227:     #radio buttons/text box for assigning points for a section or class.
                   3228:     #handles different parts of a problem
1.375     albertel 3229:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3230:     my %weight = ();
                   3231:     my $ctsparts = 0;
1.45      ng       3232:     my %seen = ();
1.375     albertel 3233:     my @part_response_id = &flatten_responseType($responseType);
                   3234:     foreach my $part_response_id (@part_response_id) {
                   3235:     	my ($partid,$respid) = @{ $part_response_id };
                   3236: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3237: 	next if $seen{$partid};
                   3238: 	$seen{$partid}++;
1.375     albertel 3239: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3240: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3241: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3242: 
1.324     albertel 3243: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3244: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3245: 	my $ctr = 0;
1.42      ng       3246: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3247: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3248: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3249: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3250: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3251: 	    $ctr++;
                   3252: 	}
1.485     albertel 3253: 	$radio.='</tr></table>';
                   3254: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3255: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3256: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.528.2.11  raeburn  3257: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3258: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3259: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3260: 		$weight{$partid}.')"> '.
1.401     albertel 3261: 	    '<option selected="selected"> </option>'.
1.485     albertel 3262: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3263: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3264: 	    '</select></td>'.
                   3265:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3266: 	$line.='<input type="hidden" name="partid_'.
                   3267: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3268: 	$line.='<input type="hidden" name="weight_'.
                   3269: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3270: 
                   3271: 	$result.=
                   3272: 	    &Apache::loncommon::start_data_table_row()."\n".
1.528.2.11  raeburn  3273:             '<td><b>'.&mt('Part').':</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points').':</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>'.
1.485     albertel 3274: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3275: 	$ctsparts++;
1.41      ng       3276:     }
1.474     albertel 3277:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3278: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3279:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3280: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3281: 
1.44      ng       3282:     #table listing all the students in a section/class
                   3283:     #header of table
1.528.2.11  raeburn  3284:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3285:               &Apache::loncommon::start_data_table().
                   3286: 	      &Apache::loncommon::start_data_table_header_row().
                   3287: 	      '<th>'.&mt('No.').'</th>'.
                   3288: 	      '<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3289:     my (@parts) = sort(&getpartlist($symb));
                   3290:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3291:     my @partids = ();
1.41      ng       3292:     foreach my $part (@parts) {
                   3293: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.528.2.11  raeburn  3294:         my $narrowtext = &mt('Tries').'<br />';
                   3295: 	$display =~ s{^Number of Attempts}{$narrowtext}; # makes the column narrower
1.41      ng       3296: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3297: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3298:         push(@partids,$partid);
1.324     albertel 3299: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3300: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3301: 	    $result.='<th>'.
1.528.2.11  raeburn  3302: 		&mt('Score Part: [_1] (weight = [_2])',
                   3303: 		    $display_part.'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3304: 	    next;
1.485     albertel 3305: 	    
1.207     albertel 3306: 	} else {
1.485     albertel 3307: 	    if ($display =~ /Problem Status/) {
1.528.2.11  raeburn  3308: 		my $grade_status_mt = &mt('Grade Status').'<br />';
                   3309: 		$display =~ s{Problem Status}{$grade_status_mt};
1.485     albertel 3310: 	    }
                   3311: 	    my $part_mt = &mt('Part:');
                   3312: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3313: 	}
1.485     albertel 3314: 
1.474     albertel 3315: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3316:     }
1.474     albertel 3317:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3318: 
1.270     albertel 3319:     my %last_resets = 
                   3320: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3321: 
1.41      ng       3322:     #get info for each student
1.44      ng       3323:     #list all the students - with points and grade status
1.257     albertel 3324:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3325:     my $ctr = 0;
1.294     albertel 3326:     foreach (sort 
                   3327: 	     {
                   3328: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3329: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3330: 		 }
                   3331: 		 return $a cmp $b;
                   3332: 	     } (keys(%$fullname))) {
1.126     ng       3333: 	$ctr++;
1.324     albertel 3334: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3335: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3336:     }
1.474     albertel 3337:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3338:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3339:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3340: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3341:     if (scalar(%$fullname) eq 0) {
                   3342: 	my $colspan=3+scalar(@parts);
1.433     banghart 3343: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3344:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3345: 	$result='<span class="LC_warning">'.
1.485     albertel 3346: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3347: 	        $section_display, $stu_status).
1.433     banghart 3348: 	    '</span>';
1.96      albertel 3349:     }
1.324     albertel 3350:     $result.=&show_grading_menu_form($symb);
1.41      ng       3351:     return $result;
                   3352: }
                   3353: 
1.44      ng       3354: #--- call by previous routine to display each student
1.41      ng       3355: sub viewstudentgrade {
1.324     albertel 3356:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3357:     my ($uname,$udom) = split(/:/,$student);
                   3358:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3359:     my %aggregates = (); 
1.474     albertel 3360:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3361: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3362: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3363: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3364: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3365: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3366:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3367:     foreach my $apart (@$parts) {
                   3368: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3369: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3370:         $result.='<td align="center">';
1.269     raeburn  3371:         my ($aggtries,$totaltries);
                   3372:         unless (exists($aggregates{$part})) {
1.270     albertel 3373: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3374: 
                   3375: 	    $aggtries = $totaltries;
1.269     raeburn  3376:             if ($$last_resets{$part}) {  
1.270     albertel 3377:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3378: 					   $part);
                   3379:             }
1.269     raeburn  3380:             $result.='<input type="hidden" name="'.
                   3381:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3382:             $result.='<input type="hidden" name="'.
                   3383:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3384:             $aggregates{$part} = 1;
                   3385:         }
1.41      ng       3386: 	if ($type eq 'awarded') {
1.320     albertel 3387: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3388: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3389: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3390: 	    $result.='<input type="text" name="'.
1.89      albertel 3391: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3392: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3393: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3394: 	} elsif ($type eq 'solved') {
                   3395: 	    my ($status,$foo)=split(/_/,$score,2);
                   3396: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3397: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3398: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3399: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3400: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3401: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3402: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3403: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3404: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3405: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3406: 	} else {
                   3407: 	    $result.='<input type="hidden" name="'.
                   3408: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3409: 		    "\n";
1.233     albertel 3410: 	    $result.='<input type="text" name="'.
1.122     ng       3411: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3412: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3413: 	}
                   3414:     }
1.474     albertel 3415:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3416:     return $result;
1.38      ng       3417: }
                   3418: 
1.44      ng       3419: #--- change scores for all the students in a section/class
                   3420: #    record does not get update if unchanged
1.38      ng       3421: sub editgrades {
1.41      ng       3422:     my ($request) = @_;
                   3423: 
1.324     albertel 3424:     my $symb=&get_symb($request);
1.433     banghart 3425:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3426:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3427:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3428:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3429: 
1.477     albertel 3430:     my $result= &Apache::loncommon::start_data_table().
                   3431: 	&Apache::loncommon::start_data_table_header_row().
                   3432: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3433: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3434:     my %scoreptr = (
                   3435: 		    'correct'  =>'correct_by_override',
                   3436: 		    'incorrect'=>'incorrect_by_override',
                   3437: 		    'excused'  =>'excused',
                   3438: 		    'ungraded' =>'ungraded_attempted',
                   3439: 		    'nothing'  => '',
                   3440: 		    );
1.257     albertel 3441:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3442: 
1.44      ng       3443:     my (@partid);
                   3444:     my %weight = ();
1.54      albertel 3445:     my %columns = ();
1.44      ng       3446:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3447: 
1.324     albertel 3448:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3449:     my $header;
1.257     albertel 3450:     while ($ctr < $env{'form.totalparts'}) {
                   3451: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3452: 	push(@partid,$partid);
1.257     albertel 3453: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3454: 	$ctr++;
1.54      albertel 3455:     }
1.324     albertel 3456:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3457:     foreach my $partid (@partid) {
1.478     albertel 3458: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3459: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3460: 	$columns{$partid}=2;
                   3461: 	foreach my $stores (@parts) {
                   3462: 	    my ($part,$type) = &split_part_type($stores);
                   3463: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3464: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3465: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.528.2.11  raeburn  3466: 	    $display =~ s/\[Part: \Q$part\E\]//;
                   3467:             my $narrowtext = &mt('Tries');
                   3468: 	    $display =~ s{Number of Attempts}{$narrowtext};
1.528.2.12! raeburn  3469: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
        !          3470: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3471: 	    $columns{$partid}+=2;
                   3472: 	}
                   3473:     }
                   3474:     foreach my $partid (@partid) {
1.324     albertel 3475: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3476: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3477: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3478: 	    '</th>';
1.54      albertel 3479: 
1.44      ng       3480:     }
1.477     albertel 3481:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3482: 	&Apache::loncommon::start_data_table_header_row().
                   3483: 	$header.
                   3484: 	&Apache::loncommon::end_data_table_header_row();
                   3485:     my @noupdate;
1.126     ng       3486:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3487:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3488: 	my $line;
1.257     albertel 3489: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3490: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3491: 	my %newrecord;
                   3492: 	my $updateflag = 0;
1.281     albertel 3493: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3494: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3495: 	if (!&canmodify($usec)) {
1.126     ng       3496: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3497: 	    push(@noupdate,
1.478     albertel 3498: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3499: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3500: 	    next;
                   3501: 	}
1.269     raeburn  3502:         my %aggregate = ();
                   3503:         my $aggregateflag = 0;
1.281     albertel 3504: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3505: 	foreach (@partid) {
1.257     albertel 3506: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3507: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3508: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3509: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3510: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3511: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3512: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3513: 	    my $score;
                   3514: 	    if ($partial eq '') {
1.257     albertel 3515: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3516: 	    } elsif ($partial > 0) {
                   3517: 		$score = 'correct_by_override';
                   3518: 	    } elsif ($partial == 0) {
                   3519: 		$score = 'incorrect_by_override';
                   3520: 	    }
1.257     albertel 3521: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3522: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3523: 
1.292     albertel 3524: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3525: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3526: 	    if ($dropMenu eq 'reset status' &&
                   3527: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3528: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3529: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3530: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3531: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3532: 		$updateflag = 1;
1.269     raeburn  3533:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3534:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3535:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3536:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3537:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3538:                     $aggregateflag = 1;
                   3539:                 }
1.139     albertel 3540: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3541: 		$updateflag = 1;
                   3542: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3543: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3544: 		$rec_update++;
1.125     ng       3545: 	    }
                   3546: 
1.93      albertel 3547: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3548: 		'<td align="center">'.$awarded.
                   3549: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3550: 
1.54      albertel 3551: 
                   3552: 	    my $partid=$_;
                   3553: 	    foreach my $stores (@parts) {
                   3554: 		my ($part,$type) = &split_part_type($stores);
                   3555: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3556: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3557: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3558: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3559: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3560: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3561: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3562: 		    $updateflag=1;
                   3563: 		}
1.93      albertel 3564: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3565: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3566: 	    }
1.44      ng       3567: 	}
1.477     albertel 3568: 	$line.="\n";
1.301     albertel 3569: 
                   3570: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3571: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3572: 
1.44      ng       3573: 	if ($updateflag) {
                   3574: 	    $count++;
1.257     albertel 3575: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3576: 				    $udom,$uname);
1.301     albertel 3577: 
                   3578: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3579: 					      $cnum,$udom,$uname)) {
                   3580: 		# need to figure out if should be in queue.
                   3581: 		my %record =  
                   3582: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3583: 					     $udom,$uname);
                   3584: 		my $all_graded = 1;
                   3585: 		my $none_graded = 1;
                   3586: 		foreach my $part (@parts) {
                   3587: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3588: 			$all_graded = 0;
                   3589: 		    } else {
                   3590: 			$none_graded = 0;
                   3591: 		    }
                   3592: 		}
                   3593: 
                   3594: 		if ($all_graded || $none_graded) {
                   3595: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3596: 							   $symb,$cdom,$cnum,
                   3597: 							   $udom,$uname);
                   3598: 		}
                   3599: 	    }
                   3600: 
1.477     albertel 3601: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3602: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3603: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3604: 	    $updateCtr++;
1.93      albertel 3605: 	} else {
1.477     albertel 3606: 	    push(@noupdate,
                   3607: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3608: 	    $noupdateCtr++;
1.44      ng       3609: 	}
1.269     raeburn  3610:         if ($aggregateflag) {
                   3611:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3612: 				  $cdom,$cnum);
1.269     raeburn  3613:         }
1.93      albertel 3614:     }
1.477     albertel 3615:     if (@noupdate) {
1.126     ng       3616: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3617: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3618: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3619: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3620: 	    &mt('No Changes Occurred For the Students Below').
                   3621: 	    '</td>'.
1.477     albertel 3622: 	    &Apache::loncommon::end_data_table_row();
                   3623: 	foreach my $line (@noupdate) {
                   3624: 	    $result.=
                   3625: 		&Apache::loncommon::start_data_table_row().
                   3626: 		$line.
                   3627: 		&Apache::loncommon::end_data_table_row();
                   3628: 	}
1.44      ng       3629:     }
1.477     albertel 3630:     $result .= &Apache::loncommon::end_data_table().
                   3631: 	&show_grading_menu_form($symb);
1.478     albertel 3632:     my $msg = '<p><b>'.
                   3633: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3634: 	    $rec_update,$count).'</b><br />'.
                   3635: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3636: 	'</b></p>';
1.44      ng       3637:     return $title.$msg.$result;
1.5       albertel 3638: }
1.54      albertel 3639: 
                   3640: sub split_part_type {
                   3641:     my ($partstr) = @_;
                   3642:     my ($temp,@allparts)=split(/_/,$partstr);
                   3643:     my $type=pop(@allparts);
1.439     albertel 3644:     my $part=join('_',@allparts);
1.54      albertel 3645:     return ($part,$type);
                   3646: }
                   3647: 
1.44      ng       3648: #------------- end of section for handling grading by section/class ---------
                   3649: #
                   3650: #----------------------------------------------------------------------------
                   3651: 
1.5       albertel 3652: 
1.44      ng       3653: #----------------------------------------------------------------------------
                   3654: #
                   3655: #-------------------------- Next few routines handles grading by csv upload
                   3656: #
                   3657: #--- Javascript to handle csv upload
1.27      albertel 3658: sub csvupload_javascript_reverse_associate {
1.246     albertel 3659:     my $error1=&mt('You need to specify the username or ID');
                   3660:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3661:   return(<<ENDPICK);
                   3662:   function verify(vf) {
                   3663:     var foundsomething=0;
                   3664:     var founduname=0;
1.243     albertel 3665:     var foundID=0;
1.27      albertel 3666:     for (i=0;i<=vf.nfields.value;i++) {
                   3667:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3668:       if (i==0 && tw!=0) { foundID=1; }
                   3669:       if (i==1 && tw!=0) { founduname=1; }
                   3670:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3671:     }
1.246     albertel 3672:     if (founduname==0 && foundID==0) {
                   3673: 	alert('$error1');
                   3674: 	return;
1.27      albertel 3675:     }
                   3676:     if (foundsomething==0) {
1.246     albertel 3677: 	alert('$error2');
                   3678: 	return;
1.27      albertel 3679:     }
                   3680:     vf.submit();
                   3681:   }
                   3682:   function flip(vf,tf) {
                   3683:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3684:     var i;
                   3685:     for (i=0;i<=vf.nfields.value;i++) {
                   3686:       //can not pick the same destination field for both name and domain
                   3687:       if (((i ==0)||(i ==1)) && 
                   3688:           ((tf==0)||(tf==1)) && 
                   3689:           (i!=tf) &&
                   3690:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3691:         eval('vf.f'+i+'.selectedIndex=0;')
                   3692:       }
                   3693:     }
                   3694:   }
                   3695: ENDPICK
                   3696: }
                   3697: 
                   3698: sub csvupload_javascript_forward_associate {
1.246     albertel 3699:     my $error1=&mt('You need to specify the username or ID');
                   3700:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3701:   return(<<ENDPICK);
                   3702:   function verify(vf) {
                   3703:     var foundsomething=0;
                   3704:     var founduname=0;
1.243     albertel 3705:     var foundID=0;
1.27      albertel 3706:     for (i=0;i<=vf.nfields.value;i++) {
                   3707:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3708:       if (tw==1) { foundID=1; }
                   3709:       if (tw==2) { founduname=1; }
                   3710:       if (tw>3) { foundsomething=1; }
1.27      albertel 3711:     }
1.246     albertel 3712:     if (founduname==0 && foundID==0) {
                   3713: 	alert('$error1');
                   3714: 	return;
1.27      albertel 3715:     }
                   3716:     if (foundsomething==0) {
1.246     albertel 3717: 	alert('$error2');
                   3718: 	return;
1.27      albertel 3719:     }
                   3720:     vf.submit();
                   3721:   }
                   3722:   function flip(vf,tf) {
                   3723:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3724:     var i;
                   3725:     //can not pick the same destination field twice
                   3726:     for (i=0;i<=vf.nfields.value;i++) {
                   3727:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3728:         eval('vf.f'+i+'.selectedIndex=0;')
                   3729:       }
                   3730:     }
                   3731:   }
                   3732: ENDPICK
                   3733: }
                   3734: 
1.26      albertel 3735: sub csvuploadmap_header {
1.324     albertel 3736:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3737:     my $javascript;
1.257     albertel 3738:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3739: 	$javascript=&csvupload_javascript_reverse_associate();
                   3740:     } else {
                   3741: 	$javascript=&csvupload_javascript_forward_associate();
                   3742:     }
1.45      ng       3743: 
1.324     albertel 3744:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3745:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3746:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3747:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3748:     $request->print(<<ENDPICK);
1.26      albertel 3749: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3750: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3751: $result
1.326     albertel 3752: <hr />
1.26      albertel 3753: <h3>Identify fields</h3>
                   3754: Total number of records found in file: $distotal <hr />
                   3755: Enter as many fields as you can. The system will inform you and bring you back
                   3756: to this page if the data selected is insufficient to run your class.<hr />
                   3757: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3758: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3759: <input type="hidden" name="associate"  value="" />
                   3760: <input type="hidden" name="phase"      value="three" />
                   3761: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3762: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3763: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3764: <input type="hidden" name="upfile_associate" 
1.257     albertel 3765:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3766: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3767: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3768: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3769: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3770: <hr />
                   3771: <script type="text/javascript" language="Javascript">
                   3772: $javascript
                   3773: </script>
                   3774: ENDPICK
1.118     ng       3775:     return '';
1.26      albertel 3776: 
                   3777: }
                   3778: 
                   3779: sub csvupload_fields {
1.324     albertel 3780:     my ($symb) = @_;
                   3781:     my (@parts) = &getpartlist($symb);
1.243     albertel 3782:     my @fields=(['ID','Student ID'],
                   3783: 		['username','Student Username'],
                   3784: 		['domain','Student Domain']);
1.324     albertel 3785:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3786:     foreach my $part (sort(@parts)) {
                   3787: 	my @datum;
                   3788: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3789: 	my $name=$part;
                   3790: 	if  (!$display) { $display = $name; }
                   3791: 	@datum=($name,$display);
1.244     albertel 3792: 	if ($name=~/^stores_(.*)_awarded/) {
                   3793: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3794: 	}
1.41      ng       3795: 	push(@fields,\@datum);
                   3796:     }
                   3797:     return (@fields);
1.26      albertel 3798: }
                   3799: 
                   3800: sub csvuploadmap_footer {
1.41      ng       3801:     my ($request,$i,$keyfields) =@_;
                   3802:     $request->print(<<ENDPICK);
1.26      albertel 3803: </table>
                   3804: <input type="hidden" name="nfields" value="$i" />
                   3805: <input type="hidden" name="keyfields" value="$keyfields" />
                   3806: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3807: </form>
                   3808: ENDPICK
                   3809: }
                   3810: 
1.283     albertel 3811: sub checkforfile_js {
1.528.2.11  raeburn  3812:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       3813:     my $result =<<CSVFORMJS;
                   3814: <script type="text/javascript" language="javascript">
                   3815:     function checkUpload(formname) {
                   3816: 	if (formname.upfile.value == "") {
1.528.2.11  raeburn  3817: 	    alert("$alertmsg");
1.86      ng       3818: 	    return false;
                   3819: 	}
                   3820: 	formname.submit();
                   3821:     }
                   3822:     </script>
                   3823: CSVFORMJS
1.283     albertel 3824:     return $result;
                   3825: }
                   3826: 
                   3827: sub upcsvScores_form {
                   3828:     my ($request) = shift;
1.324     albertel 3829:     my ($symb)=&get_symb($request);
1.283     albertel 3830:     if (!$symb) {return '';}
                   3831:     my $result=&checkforfile_js();
1.257     albertel 3832:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3833:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3834:     $result.=$table;
1.326     albertel 3835:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3836:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.528.2.11  raeburn  3837:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
1.86      ng       3838: 	'.</b></td></tr>'."\n";
                   3839:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3840:     my $upload=&mt("Upload Scores");
1.86      ng       3841:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3842:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3843:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3844:     $result.=<<ENDUPFORM;
1.106     albertel 3845: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3846: <input type="hidden" name="symb" value="$symb" />
                   3847: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3848: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3849: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3850: $upfile_select
1.370     www      3851: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3852: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3853: </form>
                   3854: ENDUPFORM
1.370     www      3855:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3856:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3857:     .'</td></tr></table>'."\n";
1.86      ng       3858:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3859:     $result.=&show_grading_menu_form($symb);
1.86      ng       3860:     return $result;
                   3861: }
                   3862: 
                   3863: 
1.26      albertel 3864: sub csvuploadmap {
1.41      ng       3865:     my ($request)= @_;
1.324     albertel 3866:     my ($symb)=&get_symb($request);
1.41      ng       3867:     if (!$symb) {return '';}
1.72      ng       3868: 
1.41      ng       3869:     my $datatoken;
1.257     albertel 3870:     if (!$env{'form.datatoken'}) {
1.41      ng       3871: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3872:     } else {
1.257     albertel 3873: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3874: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3875:     }
1.41      ng       3876:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3877:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3878:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3879:     my ($i,$keyfields);
                   3880:     if (@records) {
1.324     albertel 3881: 	my @fields=&csvupload_fields($symb);
1.45      ng       3882: 
1.257     albertel 3883: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3884: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3885: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3886: 							  \@fields);
                   3887: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3888: 	    chop($keyfields);
                   3889: 	} else {
                   3890: 	    unshift(@fields,['none','']);
                   3891: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3892: 							    \@fields);
1.311     banghart 3893:             foreach my $rec (@records) {
                   3894:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3895:                 if (%temp) {
                   3896:                     $keyfields=join(',',sort(keys(%temp)));
                   3897:                     last;
                   3898:                 }
                   3899:             }
1.41      ng       3900: 	}
                   3901:     }
                   3902:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3903:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3904: 
1.41      ng       3905:     return '';
1.27      albertel 3906: }
                   3907: 
1.246     albertel 3908: sub csvuploadoptions {
1.41      ng       3909:     my ($request)= @_;
1.324     albertel 3910:     my ($symb)=&get_symb($request);
1.257     albertel 3911:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3912:     my $ignore=&mt('Ignore First Line');
                   3913:     $request->print(<<ENDPICK);
                   3914: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3915: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3916: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3917: <!--
1.246     albertel 3918: <p>
                   3919: <label>
                   3920:    <input type="checkbox" name="show_full_results" />
                   3921:    Show a table of all changes
                   3922: </label>
                   3923: </p>
1.302     albertel 3924: -->
1.246     albertel 3925: <p>
                   3926: <label>
                   3927:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3928:    Overwrite any existing score
                   3929: </label>
                   3930: </p>
                   3931: ENDPICK
                   3932:     my %fields=&get_fields();
                   3933:     if (!defined($fields{'domain'})) {
1.257     albertel 3934: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3935: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3936:     }
1.257     albertel 3937:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3938: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3939: 	my $cleankey=$1;
                   3940: 	if ($cleankey eq 'command') { next; }
                   3941: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3942: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3943:     }
                   3944:     # FIXME do a check for any duplicated user ids...
                   3945:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3946:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3947: <hr /></form>'."\n");
1.324     albertel 3948:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3949:     return '';
                   3950: }
                   3951: 
                   3952: sub get_fields {
                   3953:     my %fields;
1.257     albertel 3954:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3955:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3956: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3957: 	    if ($env{'form.f'.$i} ne 'none') {
                   3958: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3959: 	    }
                   3960: 	} else {
1.257     albertel 3961: 	    if ($env{'form.f'.$i} ne 'none') {
                   3962: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3963: 	    }
                   3964: 	}
1.27      albertel 3965:     }
1.246     albertel 3966:     return %fields;
                   3967: }
                   3968: 
                   3969: sub csvuploadassign {
                   3970:     my ($request)= @_;
1.324     albertel 3971:     my ($symb)=&get_symb($request);
1.246     albertel 3972:     if (!$symb) {return '';}
1.345     bowersj2 3973:     my $error_msg = '';
1.246     albertel 3974:     &Apache::loncommon::load_tmp_file($request);
                   3975:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3976:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3977:     my %fields=&get_fields();
1.41      ng       3978:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3979:     my $courseid=$env{'request.course.id'};
1.97      albertel 3980:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3981:     my @notallowed;
1.41      ng       3982:     my @skipped;
                   3983:     my $countdone=0;
                   3984:     foreach my $grade (@gradedata) {
                   3985: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3986: 	my $domain;
                   3987: 	if ($entries{$fields{'domain'}}) {
                   3988: 	    $domain=$entries{$fields{'domain'}};
                   3989: 	} else {
1.257     albertel 3990: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3991: 	}
1.243     albertel 3992: 	$domain=~s/\s//g;
1.41      ng       3993: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3994: 	$username=~s/\s//g;
1.243     albertel 3995: 	if (!$username) {
                   3996: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3997: 	    $id=~s/\s//g;
1.243     albertel 3998: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3999: 	    $username=$ids{$id};
                   4000: 	}
1.41      ng       4001: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4002: 	    my $id=$entries{$fields{'ID'}};
                   4003: 	    $id=~s/\s//g;
                   4004: 	    if ($id) {
                   4005: 		push(@skipped,"$id:$domain");
                   4006: 	    } else {
                   4007: 		push(@skipped,"$username:$domain");
                   4008: 	    }
1.41      ng       4009: 	    next;
                   4010: 	}
1.108     albertel 4011: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4012: 	if (!&canmodify($usec)) {
                   4013: 	    push(@notallowed,"$username:$domain");
                   4014: 	    next;
                   4015: 	}
1.244     albertel 4016: 	my %points;
1.41      ng       4017: 	my %grades;
                   4018: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4019: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4020: 		$dest eq 'domain') { next; }
                   4021: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4022: 	    if ($dest=~/stores_(.*)_points/) {
                   4023: 		my $part=$1;
                   4024: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4025: 					      $symb,$domain,$username);
1.345     bowersj2 4026:                 if ($wgt) {
                   4027:                     $entries{$fields{$dest}}=~s/\s//g;
                   4028:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4029:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4030:                                           : 'correct_by_override';
1.345     bowersj2 4031:                     $grades{"resource.$part.awarded"}=$pcr;
                   4032:                     $grades{"resource.$part.solved"}=$award;
                   4033:                     $points{$part}=1;
                   4034:                 } else {
                   4035:                     $error_msg = "<br />" .
                   4036:                         &mt("Some point values were assigned"
                   4037:                             ." for problems with a weight "
                   4038:                             ."of zero. These values were "
                   4039:                             ."ignored.");
                   4040:                 }
1.244     albertel 4041: 	    } else {
                   4042: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4043: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4044: 		my $store_key=$dest;
                   4045: 		$store_key=~s/^stores/resource/;
                   4046: 		$store_key=~s/_/\./g;
                   4047: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4048: 	    }
1.41      ng       4049: 	}
1.508     www      4050: 	if (! %grades) { 
                   4051:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4052:         } else {
                   4053: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4054: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4055: 					   $env{'request.course.id'},
                   4056: 					   $domain,$username);
1.508     www      4057: 	   if ($result eq 'ok') {
                   4058: 	      $request->print('.');
                   4059: 	   } else {
                   4060: 	      $request->print("<p><span class=\"LC_error\">".
                   4061:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4062:                                   "$username:$domain",$result)."</span></p>");
                   4063: 	   }
                   4064: 	   $request->rflush();
                   4065: 	   $countdone++;
                   4066:         }
1.41      ng       4067:     }
1.508     www      4068:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
1.41      ng       4069:     if (@skipped) {
1.508     www      4070: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
1.106     albertel 4071: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4072:     }
                   4073:     if (@notallowed) {
1.508     www      4074: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
1.106     albertel 4075: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4076:     }
1.106     albertel 4077:     $request->print("<br />\n");
1.324     albertel 4078:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4079:     return $error_msg;
1.26      albertel 4080: }
1.44      ng       4081: #------------- end of section for handling csv file upload ---------
                   4082: #
                   4083: #-------------------------------------------------------------------
                   4084: #
1.122     ng       4085: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4086: #
                   4087: #--- Select a page/sequence and a student to grade
1.68      ng       4088: sub pickStudentPage {
                   4089:     my ($request) = shift;
                   4090: 
1.528.2.11  raeburn  4091:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4092:     $request->print(<<LISTJAVASCRIPT);
                   4093: <script type="text/javascript" language="javascript">
                   4094: 
                   4095: function checkPickOne(formname) {
1.76      ng       4096:     if (radioSelection(formname.student) == null) {
1.528.2.11  raeburn  4097: 	alert("$alertmsg");
1.68      ng       4098: 	return;
                   4099:     }
1.125     ng       4100:     ptr = pullDownSelection(formname.selectpage);
                   4101:     formname.page.value = formname["page"+ptr].value;
                   4102:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4103:     formname.submit();
                   4104: }
                   4105: 
                   4106: </script>
                   4107: LISTJAVASCRIPT
1.118     ng       4108:     &commonJSfunctions($request);
1.324     albertel 4109:     my ($symb) = &get_symb($request);
1.257     albertel 4110:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4111:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4112:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4113: 
1.398     albertel 4114:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4115: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4116: 
1.80      ng       4117:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4118:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4119:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4120: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4121: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4122:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4123:     my $ctr=0;
1.68      ng       4124:     foreach (@$titles) {
                   4125: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4126: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4127: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4128: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4129: 	$ctr++;
1.68      ng       4130:     }
1.485     albertel 4131:     $select.= '</select>';
1.528.2.11  raeburn  4132:     $result.='&nbsp;<b>'.&mt('Problems from').":</b> $select<br />\n";
1.485     albertel 4133: 
1.70      ng       4134:     $ctr=0;
                   4135:     foreach (@$titles) {
                   4136: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4137: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4138: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4139: 	$ctr++;
                   4140:     }
1.72      ng       4141:     $result.='<input type="hidden" name="page" />'."\n".
                   4142: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4143: 
1.485     albertel 4144:     my $options =
                   4145: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4146: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.528.2.11  raeburn  4147:     $result.='&nbsp;<b>'.&mt('View Problem Text').": </b> $options";
1.485     albertel 4148: 
                   4149:     $options =
                   4150: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4151: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4152: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.528.2.11  raeburn  4153:     $result.='&nbsp;>b>'.&mt('Submissions').": </b>$options";
1.432     banghart 4154:     
                   4155:     $result.=&build_section_inputs();
1.442     banghart 4156:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4157:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4158: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4159: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4160: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4161: 
1.528.2.11  raeburn  4162:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /><br />'."\n";
1.382     albertel 4163: 
1.80      ng       4164:     $result.='&nbsp;<input type="button" '.
1.528.2.11  raeburn  4165: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4166: 
1.68      ng       4167:     $request->print($result);
                   4168: 
1.485     albertel 4169:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4170: 	&Apache::loncommon::start_data_table().
                   4171: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4172: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4173: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4174: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4175: 	'<th>'.&nameUserString('header').'</th>'.
                   4176: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4177:  
1.76      ng       4178:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4179:     my $ptr = 1;
1.294     albertel 4180:     foreach my $student (sort 
                   4181: 			 {
                   4182: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4183: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4184: 			     }
                   4185: 			     return $a cmp $b;
                   4186: 			 } (keys(%$fullname))) {
1.68      ng       4187: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4188: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4189:                                   : '</td>');
1.126     ng       4190: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4191: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4192: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4193: 	$studentTable.=
                   4194: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4195:                          : '');
1.68      ng       4196: 	$ptr++;
                   4197:     }
1.484     albertel 4198:     if ($ptr%2 == 0) {
                   4199: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4200: 	    &Apache::loncommon::end_data_table_row();
                   4201:     }
                   4202:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4203:     $studentTable.='<input type="button" '.
1.485     albertel 4204: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.68      ng       4205: 
1.324     albertel 4206:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4207:     $request->print($studentTable);
                   4208: 
                   4209:     return '';
                   4210: }
                   4211: 
                   4212: sub getSymbMap {
1.132     bowersj2 4213:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4214: 
                   4215:     my %symbx = ();
                   4216:     my @titles = ();
1.117     bowersj2 4217:     my $minder = 0;
                   4218: 
                   4219:     # Gather every sequence that has problems.
1.240     albertel 4220:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4221: 					       1,0,1);
1.117     bowersj2 4222:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4223: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4224: 	    my $title = $minder.'.'.
                   4225: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4226: 	    push(@titles, $title); # minder in case two titles are identical
                   4227: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4228: 	    $minder++;
1.241     albertel 4229: 	}
1.68      ng       4230:     }
                   4231:     return \@titles,\%symbx;
                   4232: }
                   4233: 
1.72      ng       4234: #
                   4235: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4236: sub displayPage {
                   4237:     my ($request) = shift;
                   4238: 
1.324     albertel 4239:     my ($symb) = &get_symb($request);
1.257     albertel 4240:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4241:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4242:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4243:     my $pageTitle = $env{'form.page'};
1.103     albertel 4244:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4245:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4246:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4247: 
                   4248:     #need to make sure we have the correct data for later EXT calls, 
                   4249:     #thus invalidate the cache
                   4250:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4251:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4252:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4253:     &Apache::lonnet::clear_EXT_cache_status();
                   4254: 
1.103     albertel 4255:     if (!&canview($usec)) {
1.485     albertel 4256: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4257: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4258: 	return;
                   4259:     }
1.398     albertel 4260:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4261:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4262: 	'</h3>'."\n";
1.500     albertel 4263:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4264:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4265: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4266:     } else {
                   4267: 	delete($env{'form.CODE'});
                   4268:     }
1.71      ng       4269:     &sub_page_js($request);
                   4270:     $request->print($result);
                   4271: 
1.132     bowersj2 4272:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4273:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4274:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4275:     if (!$map) {
1.485     albertel 4276: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4277: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4278: 	return; 
                   4279:     }
1.68      ng       4280:     my $iterator = $navmap->getIterator($map->map_start(),
                   4281: 					$map->map_finish());
                   4282: 
1.71      ng       4283:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4284: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4285: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4286: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4287: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4288: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4289: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4290: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4291: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4292: 
1.382     albertel 4293:     if (defined($env{'form.CODE'})) {
                   4294: 	$studentTable.=
                   4295: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4296:     }
1.381     albertel 4297:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4298: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4299: 
1.485     albertel 4300:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4301: 	&Apache::loncommon::start_data_table().
                   4302: 	&Apache::loncommon::start_data_table_header_row().
                   4303: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4304: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4305: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4306: 
1.329     albertel 4307:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4308:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4309:     $iterator->next(); # skip the first BEGIN_MAP
                   4310:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4311:     while ($depth > 0) {
1.68      ng       4312:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4313:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4314: 
1.385     albertel 4315:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4316: 	    my $parts = $curRes->parts();
1.68      ng       4317:             my $title = $curRes->compTitle();
1.71      ng       4318: 	    my $symbx = $curRes->symb();
1.484     albertel 4319: 	    $studentTable.=
                   4320: 		&Apache::loncommon::start_data_table_row().
                   4321: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4322: 		(scalar(@{$parts}) == 1 ? '' 
                   4323: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4324: 							scalar(@{$parts}))
                   4325: 		 ).
                   4326: 		 '</td>';
1.71      ng       4327: 	    $studentTable.='<td valign="top">';
1.382     albertel 4328: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4329: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4330: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4331: 					     undef,'both',\%form);
1.71      ng       4332: 	    } else {
1.382     albertel 4333: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4334: 		$companswer =~ s|<form(.*?)>||g;
                   4335: 		$companswer =~ s|</form>||g;
1.71      ng       4336: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4337: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4338: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4339: #		}
1.116     ng       4340: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.528.2.12! raeburn  4341: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4342: 	    }
                   4343: 
1.257     albertel 4344: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4345: 
1.257     albertel 4346: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4347: 		if ($record{'version'} eq '') {
1.485     albertel 4348: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4349: 		} else {
1.116     ng       4350: 		    my %responseType = ();
                   4351: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4352: 			my @responseIds =$curRes->responseIds($partid);
                   4353: 			my @responseType =$curRes->responseType($partid);
                   4354: 			my %responseIds;
                   4355: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4356: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4357: 			}
                   4358: 			$responseType{$partid} = \%responseIds;
1.116     ng       4359: 		    }
1.148     albertel 4360: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4361: 
1.71      ng       4362: 		}
1.257     albertel 4363: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4364: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4365: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4366: 									$env{'request.course.id'},
1.71      ng       4367: 									'','.submission');
                   4368:  
                   4369: 	    }
1.103     albertel 4370: 	    if (&canmodify($usec)) {
                   4371: 		foreach my $partid (@{$parts}) {
                   4372: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4373: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4374: 		    $question++;
                   4375: 		}
1.196     albertel 4376: 		$prob++;
1.71      ng       4377: 	    }
                   4378: 	    $studentTable.='</td></tr>';
1.68      ng       4379: 
1.103     albertel 4380: 	}
1.68      ng       4381:         $curRes = $iterator->next();
                   4382:     }
                   4383: 
1.485     albertel 4384:     $studentTable.='</table>'."\n".
                   4385: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4386: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4387: 	'</form>'."\n";
1.324     albertel 4388:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4389:     $request->print($studentTable);
                   4390: 
                   4391:     return '';
1.119     ng       4392: }
                   4393: 
                   4394: sub displaySubByDates {
1.148     albertel 4395:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4396:     my $isCODE=0;
1.335     albertel 4397:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4398:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4399:     my $studentTable=&Apache::loncommon::start_data_table().
                   4400: 	&Apache::loncommon::start_data_table_header_row().
                   4401: 	'<th>'.&mt('Date/Time').'</th>'.
                   4402: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4403: 	'<th>'.&mt('Submission').'</th>'.
                   4404: 	'<th>'.&mt('Status').'</th>'.
                   4405: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4406:     my ($version);
                   4407:     my %mark;
1.148     albertel 4408:     my %orders;
1.119     ng       4409:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4410:     if (!exists($$record{'1:timestamp'})) {
1.528.2.11  raeburn  4411: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4412:     }
1.335     albertel 4413: 
                   4414:     my $interaction;
1.525     raeburn  4415:     my $no_increment = 1;
1.119     ng       4416:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4417: 	my $timestamp = 
                   4418: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4419: 	if (exists($$record{$version.':resource.0.version'})) {
                   4420: 	    $interaction = $$record{$version.':resource.0.version'};
                   4421: 	}
                   4422: 
                   4423: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4424: 		             : "$version:resource");
1.467     albertel 4425: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4426: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4427: 	if ($isCODE) {
                   4428: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4429: 	}
1.119     ng       4430: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4431: 	my @displaySub = ();
                   4432: 	foreach my $partid (@{$parts}) {
1.335     albertel 4433: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4434: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4435: 	    
                   4436: 
1.122     ng       4437: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4438: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4439: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4440: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4441: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4442: 
                   4443: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4444: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4445: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4446: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4447: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4448: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4449: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4450: 		    } else {
1.467     albertel 4451: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4452: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4453: 		    }
1.335     albertel 4454: 		    my $responseType=($isTask ? 'Task'
                   4455:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4456: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4457: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4458: 			$orders{$partid}->{$responseId}=
1.525     raeburn  4459: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
                   4460:                                        $no_increment);
1.148     albertel 4461: 		    }
1.147     albertel 4462: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4463: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4464: 		}
                   4465: 	    }
1.335     albertel 4466: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4467: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4468: 				    $$record{"$where.$partid.checkedin"},
                   4469: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4470: 					'<br />';
1.335     albertel 4471: 	    }
                   4472: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4473: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4474: 		    lc($$record{"$where.$partid.award"}).' '.
                   4475: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4476: 		    '<br />';
                   4477: 	    }
1.335     albertel 4478: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4479: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4480: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4481: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4482: 		$displaySub[2].=
                   4483: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4484: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4485: 	    }
                   4486: 	}
                   4487: 	# needed because old essay regrader has not parts info
                   4488: 	if (exists $$record{"$version:resource.regrader"}) {
                   4489: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4490: 	}
                   4491: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4492: 	if ($displaySub[2]) {
1.467     albertel 4493: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4494: 	}
1.467     albertel 4495: 	$studentTable.='&nbsp;</td>'.
                   4496: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4497:     }
1.467     albertel 4498:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4499:     return $studentTable;
1.71      ng       4500: }
                   4501: 
                   4502: sub updateGradeByPage {
                   4503:     my ($request) = shift;
                   4504: 
1.257     albertel 4505:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4506:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4507:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4508:     my $pageTitle = $env{'form.page'};
1.103     albertel 4509:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4510:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4511:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4512:     if (!&canmodify($usec)) {
1.526     raeburn  4513: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4514: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4515: 	return;
                   4516:     }
1.398     albertel 4517:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4518:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4519: 	'</h3>'."\n";
1.70      ng       4520: 
1.68      ng       4521:     $request->print($result);
                   4522: 
1.132     bowersj2 4523:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4524:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4525:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4526:     if (!$map) {
1.527     raeburn  4527: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4528: 	my ($symb)=&get_symb($request);
                   4529: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4530: 	return; 
                   4531:     }
1.71      ng       4532:     my $iterator = $navmap->getIterator($map->map_start(),
                   4533: 					$map->map_finish());
1.70      ng       4534: 
1.484     albertel 4535:     my $studentTable=
                   4536: 	&Apache::loncommon::start_data_table().
                   4537: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4538: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4539: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4540: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4541: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4542: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4543: 
                   4544:     $iterator->next(); # skip the first BEGIN_MAP
                   4545:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4546:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4547:     while ($depth > 0) {
1.71      ng       4548:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4549:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4550: 
1.385     albertel 4551:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4552: 	    my $parts = $curRes->parts();
1.71      ng       4553:             my $title = $curRes->compTitle();
                   4554: 	    my $symbx = $curRes->symb();
1.484     albertel 4555: 	    $studentTable.=
                   4556: 		&Apache::loncommon::start_data_table_row().
                   4557: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4558: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4559:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4560: 		.')').'</td>';
1.71      ng       4561: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4562: 
                   4563: 	    my %newrecord=();
                   4564: 	    my @displayPts=();
1.269     raeburn  4565:             my %aggregate = ();
                   4566:             my $aggregateflag = 0;
1.71      ng       4567: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4568: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4569: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4570: 
1.257     albertel 4571: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4572: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4573: 		my $partial = $newpts/$wgt;
                   4574: 		my $score;
                   4575: 		if ($partial > 0) {
                   4576: 		    $score = 'correct_by_override';
1.125     ng       4577: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4578: 		    $score = 'incorrect_by_override';
                   4579: 		}
1.257     albertel 4580: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4581: 		if ($dropMenu eq 'excused') {
1.71      ng       4582: 		    $partial = '';
                   4583: 		    $score = 'excused';
1.125     ng       4584: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4585: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4586: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4587: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4588: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4589: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4590: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4591: 		    $changeflag++;
                   4592: 		    $newpts = '';
1.269     raeburn  4593:                     
                   4594:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4595:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4596:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4597:                     if ($aggtries > 0) {
                   4598:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4599:                         $aggregateflag = 1;
                   4600:                     }
1.71      ng       4601: 		}
1.324     albertel 4602: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4603: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4604: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4605: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4606: 		    '&nbsp;<br />';
1.526     raeburn  4607: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4608: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4609: 		    '&nbsp;<br />';
1.71      ng       4610: 		$question++;
1.380     albertel 4611: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4612: 
1.71      ng       4613: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4614: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4615: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4616: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4617: 
                   4618: 		$changeflag++;
                   4619: 	    }
                   4620: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4621: 		my %record = 
                   4622: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4623: 					     $udom,$uname);
                   4624: 
                   4625: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4626: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4627: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4628: 		    $newrecord{'resource.CODE'} = '';
                   4629: 		}
1.257     albertel 4630: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4631: 					$udom,$uname);
1.382     albertel 4632: 		%record = &Apache::lonnet::restore($symbx,
                   4633: 						   $env{'request.course.id'},
                   4634: 						   $udom,$uname);
1.380     albertel 4635: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4636: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4637: 	    }
1.380     albertel 4638: 	    
1.269     raeburn  4639:             if ($aggregateflag) {
                   4640:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4641:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4642:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4643:             }
1.125     ng       4644: 
1.71      ng       4645: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4646: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4647: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4648: 
1.196     albertel 4649: 	    $prob++;
1.68      ng       4650: 	}
1.71      ng       4651:         $curRes = $iterator->next();
1.68      ng       4652:     }
1.98      albertel 4653: 
1.484     albertel 4654:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4655:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4656:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4657: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4658: 		  $changeflag));
1.76      ng       4659:     $request->print($grademsg.$studentTable);
1.68      ng       4660: 
1.70      ng       4661:     return '';
                   4662: }
                   4663: 
1.72      ng       4664: #-------- end of section for handling grading by page/sequence ---------
                   4665: #
                   4666: #-------------------------------------------------------------------
                   4667: 
1.75      albertel 4668: #--------------------Scantron Grading-----------------------------------
                   4669: #
                   4670: #------ start of section for handling grading by page/sequence ---------
                   4671: 
1.423     albertel 4672: =pod
                   4673: 
                   4674: =head1 Bubble sheet grading routines
                   4675: 
1.424     albertel 4676:   For this documentation:
                   4677: 
                   4678:    'scanline' refers to the full line of characters
                   4679:    from the file that we are parsing that represents one entire sheet
                   4680: 
                   4681:    'bubble line' refers to the data
                   4682:    representing the line of bubbles that are on the physical bubble sheet
                   4683: 
                   4684: 
                   4685: The overall process is that a scanned in bubble sheet data is uploaded
                   4686: into a course. When a user wants to grade, they select a
                   4687: sequence/folder of resources, a file of bubble sheet info, and pick
                   4688: one of the predefined configurations for what each scanline looks
                   4689: like.
                   4690: 
                   4691: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4692: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4693: because too light bubbling), 'double bubble' (each bubble line should
                   4694: have no more that one letter picked), invalid or duplicated CODE,
                   4695: invalid student ID
                   4696: 
                   4697: If the CODE option is used that determines the randomization of the
                   4698: homework problems, either way the student ID is looked up into a
                   4699: username:domain.
                   4700: 
                   4701: During the validation phase the instructor can choose to skip scanlines. 
                   4702: 
1.435     foxr     4703: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4704: 
                   4705:   scantron_original_filename (unmodified original file)
                   4706:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4707:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4708: 
                   4709: Also there is a separate hash nohist_scantrondata that contains extra
                   4710: correction information that isn't representable in the bubble sheet
                   4711: file (see &scantron_getfile() for more information)
                   4712: 
                   4713: After all scanlines are either valid, marked as valid or skipped, then
                   4714: foreach line foreach problem in the picked sequence, an ssi request is
                   4715: made that simulates a user submitting their selected letter(s) against
                   4716: the homework problem.
1.423     albertel 4717: 
                   4718: =over 4
                   4719: 
                   4720: 
                   4721: 
                   4722: =item defaultFormData
                   4723: 
                   4724:   Returns html hidden inputs used to hold context/default values.
                   4725: 
                   4726:  Arguments:
                   4727:   $symb - $symb of the current resource 
                   4728: 
                   4729: =cut
1.422     foxr     4730: 
1.81      albertel 4731: sub defaultFormData {
1.324     albertel 4732:     my ($symb)=@_;
1.447     foxr     4733:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4734:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4735:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4736: }
                   4737: 
1.447     foxr     4738: 
1.423     albertel 4739: =pod 
                   4740: 
                   4741: =item getSequenceDropDown
                   4742: 
                   4743:    Return html dropdown of possible sequences to grade
                   4744:  
                   4745:  Arguments:
                   4746:    $symb - $symb of the current resource 
                   4747: 
                   4748: =cut
1.422     foxr     4749: 
1.75      albertel 4750: sub getSequenceDropDown {
1.423     albertel 4751:     my ($symb)=@_;
1.75      albertel 4752:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4753:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4754:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4755:     my $ctr=0;
                   4756:     foreach (@$titles) {
                   4757: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4758: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4759: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4760: 	    '>'.$showtitle.'</option>'."\n";
                   4761: 	$ctr++;
                   4762:     }
                   4763:     $result.= '</select>';
                   4764:     return $result;
                   4765: }
                   4766: 
1.495     albertel 4767: my %bubble_lines_per_response;     # no. bubble lines for each response.
                   4768:                                    # index is "symb.part_id"
                   4769: 
                   4770: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4771: 
1.509     raeburn  4772: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4773:                                    # matchresponse or rankresponse, where 
                   4774:                                    # an individual response can have multiple 
                   4775:                                    # lines
1.503     raeburn  4776: 
                   4777: my %responsetype_per_response;     # responsetype for each response
                   4778: 
1.495     albertel 4779: # Save and restore the bubble lines array to the form env.
                   4780: 
                   4781: 
                   4782: sub save_bubble_lines {
                   4783:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4784: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4785: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4786: 	    $first_bubble_line{$line};
1.503     raeburn  4787:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4788:             $subdivided_bubble_lines{$line};
                   4789:         $env{"form.scantron.responsetype.$line"} =
                   4790:             $responsetype_per_response{$line};
1.495     albertel 4791:     }
                   4792: }
                   4793: 
                   4794: 
                   4795: sub restore_bubble_lines {
                   4796:     my $line = 0;
                   4797:     %bubble_lines_per_response = ();
                   4798:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4799: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4800: 	$bubble_lines_per_response{$line} = $value;
                   4801: 	$first_bubble_line{$line}  =
                   4802: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4803:         $subdivided_bubble_lines{$line} =
                   4804:             $env{"form.scantron.sub_bubblelines.$line"};
                   4805:         $responsetype_per_response{$line} =
                   4806:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4807: 	$line++;
                   4808:     }
                   4809: 
                   4810: }
                   4811: 
                   4812: #  Given the parsed scanline, get the response for 
                   4813: #  'answer' number n:
                   4814: 
                   4815: sub get_response_bubbles {
                   4816:     my ($parsed_line, $response)  = @_;
                   4817: 
                   4818: 
                   4819:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4820:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4821:     
                   4822:     my $selected = "";
                   4823: 
                   4824:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4825: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4826: 	$bubble_line++;
                   4827:     }
                   4828:     return $selected;
                   4829: }
1.423     albertel 4830: 
                   4831: =pod 
                   4832: 
                   4833: =item scantron_filenames
                   4834: 
                   4835:    Returns a list of the scantron files in the current course 
                   4836: 
                   4837: =cut
1.422     foxr     4838: 
1.202     albertel 4839: sub scantron_filenames {
1.257     albertel 4840:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4841:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4842:     my $getpropath = 1;
1.157     albertel 4843:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4844:                                        $getpropath);
1.202     albertel 4845:     my @possiblenames;
1.201     albertel 4846:     foreach my $filename (sort(@files)) {
1.157     albertel 4847: 	($filename)=split(/&/,$filename);
                   4848: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4849: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4850: 	push(@possiblenames,$filename);
                   4851:     }
                   4852:     return @possiblenames;
                   4853: }
                   4854: 
1.423     albertel 4855: =pod 
                   4856: 
                   4857: =item scantron_uploads
                   4858: 
                   4859:    Returns  html drop-down list of scantron files in current course.
                   4860: 
                   4861:  Arguments:
                   4862:    $file2grade - filename to set as selected in the dropdown
                   4863: 
                   4864: =cut
1.422     foxr     4865: 
1.202     albertel 4866: sub scantron_uploads {
1.209     ng       4867:     my ($file2grade) = @_;
1.202     albertel 4868:     my $result=	'<select name="scantron_selectfile">';
                   4869:     $result.="<option></option>";
                   4870:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4871: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4872:     }
                   4873:     $result.="</select>";
                   4874:     return $result;
                   4875: }
                   4876: 
1.423     albertel 4877: =pod 
                   4878: 
                   4879: =item scantron_scantab
                   4880: 
                   4881:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4882:   file.
                   4883: 
                   4884: =cut
1.422     foxr     4885: 
1.82      albertel 4886: sub scantron_scantab {
                   4887:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4888:     $result.='<option></option>'."\n";
1.518     raeburn  4889:     my @lines = &get_scantronformat_file();
                   4890:     if (@lines > 0) {
                   4891:         foreach my $line (@lines) {
                   4892:             next if (($line =~ /^\#/) || ($line eq ''));
                   4893: 	    my ($name,$descrip)=split(/:/,$line);
                   4894: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4895:         }
1.82      albertel 4896:     }
                   4897:     $result.='</select>'."\n";
1.518     raeburn  4898:     return $result;
                   4899: }
                   4900: 
                   4901: =pod
                   4902: 
                   4903: =item get_scantronformat_file
                   4904: 
                   4905:   Returns an array containing lines from the scantron format file for
                   4906:   the domain of the course.
                   4907: 
                   4908:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4909:   lines are from this file.
                   4910: 
                   4911:   Otherwise, if a default.tab has been published in RES space by the 
                   4912:   domainconfig user, lines are from this file.
                   4913: 
                   4914:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4915:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4916: 
1.518     raeburn  4917: =cut
                   4918: 
                   4919: sub get_scantronformat_file {
                   4920:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4921:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   4922:     my $gottab = 0;
                   4923:     my @lines;
                   4924:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4925:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4926:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4927:             if ($formatfile ne '-1') {
                   4928:                 @lines = split("\n",$formatfile,-1);
                   4929:                 $gottab = 1;
                   4930:             }
                   4931:         }
                   4932:     }
                   4933:     if (!$gottab) {
                   4934:         my $confname = $cdom.'-domainconfig';
                   4935:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4936:         my $formatfile =  &Apache::lonnet::getfile($default);
                   4937:         if ($formatfile ne '-1') {
                   4938:             @lines = split("\n",$formatfile,-1);
                   4939:             $gottab = 1;
                   4940:         }
                   4941:     }
                   4942:     if (!$gottab) {
1.519     raeburn  4943:         my @domains = &Apache::lonnet::current_machine_domains();
                   4944:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4945:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4946:             @lines = <$fh>;
                   4947:             close($fh);
                   4948:         } else {
                   4949:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   4950:             @lines = <$fh>;
                   4951:             close($fh);
                   4952:         }
1.518     raeburn  4953:     }
                   4954:     return @lines;
1.82      albertel 4955: }
                   4956: 
1.423     albertel 4957: =pod 
                   4958: 
                   4959: =item scantron_CODElist
                   4960: 
                   4961:   Returns html drop down of the saved CODE lists from current course,
                   4962:   generated from earlier printings.
                   4963: 
                   4964: =cut
1.422     foxr     4965: 
1.186     albertel 4966: sub scantron_CODElist {
1.257     albertel 4967:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4968:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4969:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4970:     my $namechoice='<option></option>';
1.225     albertel 4971:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4972: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4973: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4974: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4975:     }
                   4976:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4977:     return $namechoice;
                   4978: }
                   4979: 
1.423     albertel 4980: =pod 
                   4981: 
                   4982: =item scantron_CODEunique
                   4983: 
                   4984:   Returns the html for "Each CODE to be used once" radio.
                   4985: 
                   4986: =cut
1.422     foxr     4987: 
1.186     albertel 4988: sub scantron_CODEunique {
1.528.2.1  raeburn  4989:     my $result='<span class="LC_nobreak">
1.272     albertel 4990:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4991:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4992:                 </span>
1.528.2.1  raeburn  4993:                 <span class="LC_nobreak">
1.272     albertel 4994:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4995:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4996:                 </span>';
1.186     albertel 4997:     return $result;
                   4998: }
1.423     albertel 4999: 
                   5000: =pod 
                   5001: 
                   5002: =item scantron_selectphase
                   5003: 
                   5004:   Generates the initial screen to start the bubble sheet process.
                   5005:   Allows for - starting a grading run.
1.424     albertel 5006:              - downloading existing scan data (original, corrected
1.423     albertel 5007:                                                 or skipped info)
                   5008: 
                   5009:              - uploading new scan data
                   5010: 
                   5011:  Arguments:
                   5012:   $r          - The Apache request object
                   5013:   $file2grade - name of the file that contain the scanned data to score
                   5014: 
                   5015: =cut
1.186     albertel 5016: 
1.75      albertel 5017: sub scantron_selectphase {
1.209     ng       5018:     my ($r,$file2grade) = @_;
1.324     albertel 5019:     my ($symb)=&get_symb($r);
1.75      albertel 5020:     if (!$symb) {return '';}
1.423     albertel 5021:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 5022:     my $default_form_data=&defaultFormData($symb);
                   5023:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5024:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5025:     my $format_selector=&scantron_scantab();
1.186     albertel 5026:     my $CODE_selector=&scantron_CODElist();
                   5027:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5028:     my $result;
1.422     foxr     5029: 
1.513     foxr     5030:     $ssi_error = 0;
                   5031: 
1.422     foxr     5032:     # Chunk of form to prompt for a file to grade and how:
                   5033: 
1.489     albertel 5034:     $result.= '
                   5035:     <br />
                   5036:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5037:     <input type="hidden" name="command" value="scantron_warning" />
                   5038:     '.$default_form_data.'
                   5039:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5040:        '.&Apache::loncommon::start_data_table_header_row().'
                   5041:             <th colspan="2">
1.492     albertel 5042:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5043:             </th>
                   5044:        '.&Apache::loncommon::end_data_table_header_row().'
                   5045:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5046:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5047:        '.&Apache::loncommon::end_data_table_row().'
                   5048:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5049:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5050:        '.&Apache::loncommon::end_data_table_row().'
                   5051:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5052:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5053:        '.&Apache::loncommon::end_data_table_row().'
                   5054:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5055:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5056:        '.&Apache::loncommon::end_data_table_row().'
                   5057:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5058:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5059:        '.&Apache::loncommon::end_data_table_row().'
                   5060:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5061: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5062:             <td>
1.492     albertel 5063: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5064:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5065:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5066: 	    </td>
1.489     albertel 5067:        '.&Apache::loncommon::end_data_table_row().'
                   5068:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5069:             <td colspan="2">
1.492     albertel 5070:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
1.162     albertel 5071:             </td>
1.489     albertel 5072:        '.&Apache::loncommon::end_data_table_row().'
                   5073:     '.&Apache::loncommon::end_data_table().'
                   5074:     </form>
                   5075: ';
1.162     albertel 5076:    
                   5077:     $r->print($result);
                   5078: 
1.257     albertel 5079:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5080:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5081: 
1.422     foxr     5082: 	# Chunk of form to prompt for a scantron file upload.
                   5083: 
1.489     albertel 5084:         $r->print('
                   5085:     <br />
                   5086:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5087:        '.&Apache::loncommon::start_data_table_header_row().'
                   5088:             <th>
1.492     albertel 5089:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
1.489     albertel 5090:             </th>
                   5091:        '.&Apache::loncommon::end_data_table_header_row().'
                   5092:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5093:             <td>
1.489     albertel 5094: ');
1.324     albertel 5095:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5096:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5097:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5098:     $r->print('
1.174     albertel 5099:               <script type="text/javascript" language="javascript">
                   5100:     function checkUpload(formname) {
                   5101: 	if (formname.upfile.value == "") {
1.492     albertel 5102: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5103: 	    return false;
                   5104: 	}
                   5105: 	formname.submit();
                   5106:     }
                   5107:               </script>
                   5108: 
1.492     albertel 5109:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5110:                 '.$default_form_data.'
                   5111:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5112:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5113:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5114:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5115:                 <br />
1.492     albertel 5116:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.174     albertel 5117:               </form>
1.492     albertel 5118: ');
1.162     albertel 5119: 
1.489     albertel 5120:         $r->print('
1.162     albertel 5121:             </td>
1.489     albertel 5122:        '.&Apache::loncommon::end_data_table_row().'
                   5123:        '.&Apache::loncommon::end_data_table().'
                   5124: ');
1.162     albertel 5125:     }
1.422     foxr     5126: 
                   5127:     # Chunk of the form that prompts to view a scoring office file,
                   5128:     # corrected file, skipped records in a file.
                   5129: 
1.489     albertel 5130:     $r->print('
                   5131:    <br />
                   5132:    <form action="/adm/grades" name="scantron_download">
                   5133:      '.$default_form_data.'
                   5134:      <input type="hidden" name="command" value="scantron_download" />
                   5135:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5136:        '.&Apache::loncommon::start_data_table_header_row().'
                   5137:               <th>
1.492     albertel 5138:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5139:               </th>
                   5140:        '.&Apache::loncommon::end_data_table_header_row().'
                   5141:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5142:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5143:                 <br />
1.492     albertel 5144:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5145:        '.&Apache::loncommon::end_data_table_row().'
                   5146:      '.&Apache::loncommon::end_data_table().'
                   5147:    </form>
                   5148:    <br />
                   5149: ');
1.162     albertel 5150: 
1.457     banghart 5151:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5152: 
1.528     raeburn  5153:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5154:              $default_form_data."\n".
                   5155:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5156:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5157:              '<th colspan="2">
                   5158:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
                   5159:              '</th>'."\n".
                   5160:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5161:               &Apache::loncommon::start_data_table_row()."\n".
                   5162:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5163:               '<td> '.$sequence_selector.' </td>'.
                   5164:               &Apache::loncommon::end_data_table_row()."\n".
                   5165:               &Apache::loncommon::start_data_table_row()."\n".
                   5166:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5167:               '<td> '.$file_selector.' </td>'."\n".
                   5168:               &Apache::loncommon::end_data_table_row()."\n".
                   5169:               &Apache::loncommon::start_data_table_row()."\n".
                   5170:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5171:               '<td> '.$format_selector.' </td>'."\n".
                   5172:               &Apache::loncommon::end_data_table_row()."\n".
                   5173:               &Apache::loncommon::start_data_table_row()."\n".
                   5174:               '<td colspan="2">'."\n".
                   5175:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
                   5176:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
                   5177:               '</td>'."\n".
                   5178:               &Apache::loncommon::end_data_table_row()."\n".
                   5179:               &Apache::loncommon::end_data_table()."\n".
                   5180:               '</form><br />');
1.457     banghart 5181:     $r->print($grading_menu_button);
1.523     raeburn  5182:     return;
1.75      albertel 5183: }
                   5184: 
1.423     albertel 5185: =pod
                   5186: 
                   5187: =item get_scantron_config
                   5188: 
                   5189:    Parse and return the scantron configuration line selected as a
                   5190:    hash of configuration file fields.
                   5191: 
                   5192:  Arguments:
                   5193:     which - the name of the configuration to parse from the file.
                   5194: 
                   5195: 
                   5196:  Returns:
                   5197:             If the named configuration is not in the file, an empty
                   5198:             hash is returned.
                   5199:     a hash with the fields
                   5200:       name         - internal name for the this configuration setup
                   5201:       description  - text to display to operator that describes this config
                   5202:       CODElocation - if 0 or the string 'none'
                   5203:                           - no CODE exists for this config
                   5204:                      if -1 || the string 'letter'
                   5205:                           - a CODE exists for this config and is
                   5206:                             a string of letters
                   5207:                      Unsupported value (but planned for future support)
                   5208:                           if a positive integer
                   5209:                                - The CODE exists as the first n items from
                   5210:                                  the question section of the form
                   5211:                           if the string 'number'
                   5212:                                - The CODE exists for this config and is
                   5213:                                  a string of numbers
                   5214:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5215:                      the CODE starts
                   5216:       CODElength  - length of the CODE
                   5217:       IDstart     - column where the student ID number starts
                   5218:       IDlength    - length of the student ID info
                   5219:       Qstart      - column where the information from the bubbled
                   5220:                     'questions' start
                   5221:       Qlength     - number of columns comprising a single bubble line from
                   5222:                     the sheet. (usually either 1 or 10)
1.424     albertel 5223:       Qon         - either a single character representing the character used
1.423     albertel 5224:                     to signal a bubble was chosen in the positional setup, or
                   5225:                     the string 'letter' if the letter of the chosen bubble is
                   5226:                     in the final, or 'number' if a number representing the
                   5227:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5228:       Qoff        - the character used to represent that a bubble was
                   5229:                     left blank
1.423     albertel 5230:       PaperID     - if the scanning process generates a unique number for each
                   5231:                     sheet scanned the column that this ID number starts in
                   5232:       PaperIDlength - number of columns that comprise the unique ID number
                   5233:                       for the sheet of paper
1.424     albertel 5234:       FirstName   - column that the first name starts in
1.423     albertel 5235:       FirstNameLength - number of columns that the first name spans
                   5236:  
                   5237:       LastName    - column that the last name starts in
                   5238:       LastNameLength - number of columns that the last name spans
                   5239: 
                   5240: =cut
1.422     foxr     5241: 
1.82      albertel 5242: sub get_scantron_config {
                   5243:     my ($which) = @_;
1.518     raeburn  5244:     my @lines = &get_scantronformat_file();
1.82      albertel 5245:     my %config;
1.157     albertel 5246:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5247:     foreach my $line (@lines) {
1.82      albertel 5248: 	my ($name,$descrip)=split(/:/,$line);
                   5249: 	if ($name ne $which ) { next; }
                   5250: 	chomp($line);
                   5251: 	my @config=split(/:/,$line);
                   5252: 	$config{'name'}=$config[0];
                   5253: 	$config{'description'}=$config[1];
                   5254: 	$config{'CODElocation'}=$config[2];
                   5255: 	$config{'CODEstart'}=$config[3];
                   5256: 	$config{'CODElength'}=$config[4];
                   5257: 	$config{'IDstart'}=$config[5];
                   5258: 	$config{'IDlength'}=$config[6];
                   5259: 	$config{'Qstart'}=$config[7];
1.497     foxr     5260:  	$config{'Qlength'}=$config[8];
1.82      albertel 5261: 	$config{'Qoff'}=$config[9];
                   5262: 	$config{'Qon'}=$config[10];
1.157     albertel 5263: 	$config{'PaperID'}=$config[11];
                   5264: 	$config{'PaperIDlength'}=$config[12];
                   5265: 	$config{'FirstName'}=$config[13];
                   5266: 	$config{'FirstNamelength'}=$config[14];
                   5267: 	$config{'LastName'}=$config[15];
                   5268: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5269: 	last;
                   5270:     }
                   5271:     return %config;
                   5272: }
                   5273: 
1.423     albertel 5274: =pod 
                   5275: 
                   5276: =item username_to_idmap
                   5277: 
                   5278:     creates a hash keyed by student id with values of the corresponding
                   5279:     student username:domain.
                   5280: 
                   5281:   Arguments:
                   5282: 
                   5283:     $classlist - reference to the class list hash. This is a hash
                   5284:                  keyed by student name:domain  whose elements are references
1.424     albertel 5285:                  to arrays containing various chunks of information
1.423     albertel 5286:                  about the student. (See loncoursedata for more info).
                   5287: 
                   5288:   Returns
                   5289:     %idmap - the constructed hash
                   5290: 
                   5291: =cut
                   5292: 
1.82      albertel 5293: sub username_to_idmap {
                   5294:     my ($classlist)= @_;
                   5295:     my %idmap;
                   5296:     foreach my $student (keys(%$classlist)) {
                   5297: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5298: 	    $student;
                   5299:     }
                   5300:     return %idmap;
                   5301: }
1.423     albertel 5302: 
                   5303: =pod
                   5304: 
1.424     albertel 5305: =item scantron_fixup_scanline
1.423     albertel 5306: 
                   5307:    Process a requested correction to a scanline.
                   5308: 
                   5309:   Arguments:
                   5310:     $scantron_config   - hash from &get_scantron_config()
                   5311:     $scan_data         - hash of correction information 
                   5312:                           (see &scantron_getfile())
                   5313:     $line              - existing scanline
                   5314:     $whichline         - line number of the passed in scanline
                   5315:     $field             - type of change to process 
                   5316:                          (either 
                   5317:                           'ID'     -> correct the student ID number
                   5318:                           'CODE'   -> correct the CODE
                   5319:                           'answer' -> fixup the submitted answers)
                   5320:     
                   5321:    $args               - hash of additional info,
                   5322:                           - 'ID' 
                   5323:                                'newid' -> studentID to use in replacement
1.424     albertel 5324:                                           of existing one
1.423     albertel 5325:                           - 'CODE' 
                   5326:                                'CODE_ignore_dup' - set to true if duplicates
                   5327:                                                    should be ignored.
                   5328: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5329:                                         if the existing unfound code should
1.423     albertel 5330:                                         be used as is
                   5331:                           - 'answer'
                   5332:                                'response' - new answer or 'none' if blank
                   5333:                                'question' - the bubble line to change
1.503     raeburn  5334:                                'questionnum' - the question identifier,
                   5335:                                                may include subquestion. 
1.423     albertel 5336: 
                   5337:   Returns:
                   5338:     $line - the modified scanline
                   5339: 
                   5340:   Side effects: 
                   5341:     $scan_data - may be updated
                   5342: 
                   5343: =cut
                   5344: 
1.82      albertel 5345: 
1.157     albertel 5346: sub scantron_fixup_scanline {
                   5347:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5348:     if ($field eq 'ID') {
                   5349: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5350: 	    return ($line,1,'New value too large');
1.157     albertel 5351: 	}
                   5352: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5353: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5354: 				     $args->{'newid'});
                   5355: 	}
                   5356: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5357: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5358: 	if ($args->{'newid'}=~/^\s*$/) {
                   5359: 	    &scan_data($scan_data,"$whichline.user",
                   5360: 		       $args->{'username'}.':'.$args->{'domain'});
                   5361: 	}
1.186     albertel 5362:     } elsif ($field eq 'CODE') {
1.192     albertel 5363: 	if ($args->{'CODE_ignore_dup'}) {
                   5364: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5365: 	}
                   5366: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5367: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5368: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5369: 		return ($line,1,'New CODE value too large');
                   5370: 	    }
                   5371: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5372: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5373: 	    }
                   5374: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5375: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5376: 	}
1.157     albertel 5377:     } elsif ($field eq 'answer') {
1.497     foxr     5378: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5379: 	my $off=$scantron_config->{'Qoff'};
                   5380: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5381: 	my $answer=${off}x$length;
                   5382: 	if ($args->{'response'} eq 'none') {
                   5383: 	    &scan_data($scan_data,
1.503     raeburn  5384: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5385: 	} else {
                   5386: 	    if ($on eq 'letter') {
                   5387: 		my @alphabet=('A'..'Z');
                   5388: 		$answer=$alphabet[$args->{'response'}];
                   5389: 	    } elsif ($on eq 'number') {
                   5390: 		$answer=$args->{'response'}+1;
                   5391: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5392: 	    } else {
1.497     foxr     5393: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5394: 	    }
1.497     foxr     5395: 	    &scan_data($scan_data,
1.503     raeburn  5396: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5397: 	}
1.497     foxr     5398: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5399: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5400:     }
                   5401:     return $line;
                   5402: }
1.423     albertel 5403: 
                   5404: =pod
                   5405: 
                   5406: =item scan_data
                   5407: 
                   5408:     Edit or look up  an item in the scan_data hash.
                   5409: 
                   5410:   Arguments:
                   5411:     $scan_data  - The hash (see scantron_getfile)
                   5412:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5413:                   scantronfilename_key).
1.423     albertel 5414:     $data        - New value of the hash entry.
                   5415:     $delete      - If true, the entry is removed from the hash.
                   5416: 
                   5417:   Returns:
                   5418:     The new value of the hash table field (undefined if deleted).
                   5419: 
                   5420: =cut
                   5421: 
                   5422: 
1.157     albertel 5423: sub scan_data {
                   5424:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5425:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5426:     if (defined($value)) {
                   5427: 	$scan_data->{$filename.'_'.$key} = $value;
                   5428:     }
                   5429:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5430:     return $scan_data->{$filename.'_'.$key};
                   5431: }
1.423     albertel 5432: 
1.495     albertel 5433: # ----- These first few routines are general use routines.----
                   5434: 
                   5435: # Return the number of occurences of a pattern in a string.
                   5436: 
                   5437: sub occurence_count {
                   5438:     my ($string, $pattern) = @_;
                   5439: 
                   5440:     my @matches = ($string =~ /$pattern/g);
                   5441: 
                   5442:     return scalar(@matches);
                   5443: }
                   5444: 
                   5445: 
                   5446: # Take a string known to have digits and convert all the
                   5447: # digits into letters in the range J,A..I.
                   5448: 
                   5449: sub digits_to_letters {
                   5450:     my ($input) = @_;
                   5451: 
                   5452:     my @alphabet = ('J', 'A'..'I');
                   5453: 
                   5454:     my @input    = split(//, $input);
                   5455:     my $output ='';
                   5456:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5457: 	if ($input[$i] =~ /\d/) {
                   5458: 	    $output .= $alphabet[$input[$i]];
                   5459: 	} else {
                   5460: 	    $output .= $input[$i];
                   5461: 	}
                   5462:     }
                   5463:     return $output;
                   5464: }
                   5465: 
1.423     albertel 5466: =pod 
                   5467: 
                   5468: =item scantron_parse_scanline
                   5469: 
                   5470:   Decodes a scanline from the selected scantron file
                   5471: 
                   5472:  Arguments:
                   5473:     line             - The text of the scantron file line to process
                   5474:     whichline        - Line number
                   5475:     scantron_config  - Hash describing the format of the scantron lines.
                   5476:     scan_data        - Hash of extra information about the scanline
                   5477:                        (see scantron_getfile for more information)
                   5478:     just_header      - True if should not process question answers but only
                   5479:                        the stuff to the left of the answers.
                   5480:  Returns:
                   5481:    Hash containing the result of parsing the scanline
                   5482: 
                   5483:    Keys are all proceeded by the string 'scantron.'
                   5484: 
                   5485:        CODE    - the CODE in use for this scanline
                   5486:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5487:                  by the operator
                   5488:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5489:                             CODEs were selected, but the usage has been
                   5490:                             forced by the operator
                   5491:        ID  - student ID
                   5492:        PaperID - if used, the ID number printed on the sheet when the 
                   5493:                  paper was scanned
                   5494:        FirstName - first name from the sheet
                   5495:        LastName  - last name from the sheet
                   5496: 
                   5497:      if just_header was not true these key may also exist
                   5498: 
1.447     foxr     5499:        missingerror - a list of bubble ranges that are considered to be answers
                   5500:                       to a single question that don't have any bubbles filled in.
                   5501:                       Of the form questionnumber:firstbubblenumber:count.
                   5502:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5503:                       to a single question that have more than one bubble filled in.
                   5504:                       Of the form questionnumber::firstbubblenumber:count
                   5505:    
                   5506:                 In the above, count is the number of bubble responses in the
                   5507:                 input line needed to represent the possible answers to the question.
                   5508:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5509:                 per line would have count = 2.
                   5510: 
1.423     albertel 5511:        maxquest     - the number of the last bubble line that was parsed
                   5512: 
                   5513:        (<number> starts at 1)
                   5514:        <number>.answer - zero or more letters representing the selected
                   5515:                          letters from the scanline for the bubble line 
                   5516:                          <number>.
                   5517:                          if blank there was either no bubble or there where
                   5518:                          multiple bubbles, (consult the keys missingerror and
                   5519:                          doubleerror if this is an error condition)
                   5520: 
                   5521: =cut
                   5522: 
1.82      albertel 5523: sub scantron_parse_scanline {
1.423     albertel 5524:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5525: 
1.82      albertel 5526:     my %record;
1.528.2.11  raeburn  5527:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5528:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5529:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5530:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5531: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5532: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5533: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5534: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5535: 	    $record{'scantron.CODE'}=substr($data,
                   5536: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5537: 					    $$scantron_config{'CODElength'});
1.191     albertel 5538: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5539: 		$record{'scantron.useCODE'}=1;
                   5540: 	    }
1.192     albertel 5541: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5542: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5543: 	    }
1.82      albertel 5544: 	} else {
                   5545: 	    #FIXME interpret first N questions
                   5546: 	}
                   5547:     }
1.83      albertel 5548:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5549: 				  $$scantron_config{'IDlength'});
1.157     albertel 5550:     $record{'scantron.PaperID'}=
                   5551: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5552: 	       $$scantron_config{'PaperIDlength'});
                   5553:     $record{'scantron.FirstName'}=
                   5554: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5555: 	       $$scantron_config{'FirstNamelength'});
                   5556:     $record{'scantron.LastName'}=
                   5557: 	substr($data,$$scantron_config{'LastName'}-1,
                   5558: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5559:     if ($just_header) { return \%record; }
1.194     albertel 5560: 
1.82      albertel 5561:     my @alphabet=('A'..'Z');
                   5562:     my $questnum=0;
1.447     foxr     5563:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5564: 
1.470     foxr     5565:     chomp($questions);		# Get rid of any trailing \n.
                   5566:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5567:     while (length($questions)) {
1.447     foxr     5568: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5569:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5570:                              || 1;
                   5571:         $questnum++;
                   5572:         my $quest_id = $questnum;
                   5573:         my $currentquest = substr($questions,0,$answer_length);
                   5574:         $questions       = substr($questions,$answer_length);
                   5575:         if (length($currentquest) < $answer_length) { next; }
                   5576: 
                   5577:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5578:             my $subquestnum = 1;
                   5579:             my $subquestions = $currentquest;
                   5580:             my @subanswers_needed = 
                   5581:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5582:             foreach my $subans (@subanswers_needed) {
                   5583:                 my $subans_length =
                   5584:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5585:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5586:                 $subquestions   = substr($subquestions,$subans_length);
                   5587:                 $quest_id = "$questnum.$subquestnum";
                   5588:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5589:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5590:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5591:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5592:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5593:                 } else {
                   5594:                     $ansnum = &scantron_validator_positional($ansnum,
                   5595:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5596:                 }
                   5597:                 $subquestnum ++;
                   5598:             }
                   5599:         } else {
                   5600:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5601:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5602:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5603:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5604:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5605:             } else {
                   5606:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5607:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5608:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5609:             }
                   5610:         }
                   5611:     }
                   5612:     $record{'scantron.maxquest'}=$questnum;
                   5613:     return \%record;
                   5614: }
1.447     foxr     5615: 
1.503     raeburn  5616: sub scantron_validator_lettnum {
                   5617:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5618:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5619: 
                   5620:     # Qon 'letter' implies for each slot in currquest we have:
                   5621:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5622:     #    about anything else (esp. a value of Qoff) for missing
                   5623:     #    bubbles.
                   5624:     #
                   5625:     # Qon 'number' implies each slot gives a digit that indexes the
                   5626:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5627:     #    and * or ? for double bubbles on a single line.
                   5628:     #
1.447     foxr     5629: 
1.503     raeburn  5630:     my $matchon;
                   5631:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5632:         $matchon = '[A-Z]';
                   5633:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5634:         $matchon = '\d';
                   5635:     }
                   5636:     my $occurrences = 0;
                   5637:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5638:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5639:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5640:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5641:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5642:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5643:         my @singlelines = split('',$currquest);
                   5644:         foreach my $entry (@singlelines) {
                   5645:             $occurrences = &occurence_count($entry,$matchon);
                   5646:             if ($occurrences > 1) {
                   5647:                 last;
                   5648:             }
                   5649:         } 
                   5650:     } else {
                   5651:         $occurrences = &occurence_count($currquest,$matchon); 
                   5652:     }
                   5653:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5654:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5655:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5656:             my $bubble = substr($currquest,$ans,1);
                   5657:             if ($bubble =~ /$matchon/ ) {
                   5658:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5659:                     if ($bubble == 0) {
                   5660:                         $bubble = 10; 
                   5661:                     }
                   5662:                     $record->{"scantron.$ansnum.answer"} = 
                   5663:                         $alphabet->[$bubble-1];
                   5664:                 } else {
                   5665:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5666:                 }
                   5667:             } else {
                   5668:                 $record->{"scantron.$ansnum.answer"}='';
                   5669:             }
                   5670:             $ansnum++;
                   5671:         }
                   5672:     } elsif (!defined($currquest)
                   5673:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5674:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5675:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5676:             $record->{"scantron.$ansnum.answer"}='';
                   5677:             $ansnum++;
                   5678:         }
                   5679:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5680:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5681:         }
                   5682:     } else {
                   5683:         if ($$scantron_config{'Qon'} eq 'number') {
                   5684:             $currquest = &digits_to_letters($currquest);            
                   5685:         }
                   5686:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5687:             my $bubble = substr($currquest,$ans,1);
                   5688:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5689:             $ansnum++;
                   5690:         }
                   5691:     }
                   5692:     return $ansnum;
                   5693: }
1.447     foxr     5694: 
1.503     raeburn  5695: sub scantron_validator_positional {
                   5696:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5697:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5698: 
1.503     raeburn  5699:     # Otherwise there's a positional notation;
                   5700:     # each bubble line requires Qlength items, and there are filled in
                   5701:     # bubbles for each case where there 'Qon' characters.
                   5702:     #
1.447     foxr     5703: 
1.503     raeburn  5704:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5705: 
1.503     raeburn  5706:     # If the split only gives us one element.. the full length of the
                   5707:     # answer string, no bubbles are filled in:
1.447     foxr     5708: 
1.507     raeburn  5709:     if ($answers_needed eq '') {
                   5710:         return;
                   5711:     }
                   5712: 
1.503     raeburn  5713:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5714:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5715:             $record->{"scantron.$ansnum.answer"}='';
                   5716:             $ansnum++;
                   5717:         }
                   5718:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5719:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5720:         }
                   5721:     } elsif (scalar(@array) == 2) {
                   5722:         my $location = length($array[0]);
                   5723:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5724:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5725:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5726:             if ($ans eq $line_num) {
                   5727:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5728:             } else {
                   5729:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5730:             }
                   5731:             $ansnum++;
                   5732:          }
                   5733:     } else {
                   5734:         #  If there's more than one instance of a bubble character
                   5735:         #  That's a double bubble; with positional notation we can
                   5736:         #  record all the bubbles filled in as well as the
                   5737:         #  fact this response consists of multiple bubbles.
                   5738:         #
                   5739:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5740:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5741:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5742:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5743:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5744:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5745:             my $doubleerror = 0;
                   5746:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5747:                    (!$doubleerror)) {
                   5748:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5749:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5750:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5751:                if (length(@currarray) > 2) {
                   5752:                    $doubleerror = 1;
                   5753:                } 
                   5754:             }
                   5755:             if ($doubleerror) {
                   5756:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5757:             }
                   5758:         } else {
                   5759:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5760:         }
                   5761:         my $item = $ansnum;
                   5762:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5763:             $record->{"scantron.$item.answer"} = '';
                   5764:             $item ++;
                   5765:         }
1.447     foxr     5766: 
1.503     raeburn  5767:         my @ans=@array;
                   5768:         my $i=0;
                   5769:         my $increment = 0;
                   5770:         while ($#ans) {
                   5771:             $i+=length($ans[0]) + $increment;
                   5772:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5773:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5774:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5775:             shift(@ans);
                   5776:             $increment = 1;
                   5777:         }
                   5778:         $ansnum += $answers_needed;
1.82      albertel 5779:     }
1.503     raeburn  5780:     return $ansnum;
1.82      albertel 5781: }
                   5782: 
1.423     albertel 5783: =pod
                   5784: 
                   5785: =item scantron_add_delay
                   5786: 
                   5787:    Adds an error message that occurred during the grading phase to a
                   5788:    queue of messages to be shown after grading pass is complete
                   5789: 
                   5790:  Arguments:
1.424     albertel 5791:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5792:    $scanline    - the scanline that caused the error
                   5793:    $errormesage - the error message
                   5794:    $errorcode   - a numeric code for the error
                   5795: 
                   5796:  Side Effects:
1.424     albertel 5797:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5798: 
                   5799: =cut
                   5800: 
1.82      albertel 5801: sub scantron_add_delay {
1.140     albertel 5802:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5803:     push(@$delayqueue,
                   5804: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5805: 	  'ecode' => $errorcode }
                   5806: 	 );
1.82      albertel 5807: }
                   5808: 
1.423     albertel 5809: =pod
                   5810: 
                   5811: =item scantron_find_student
                   5812: 
1.424     albertel 5813:    Finds the username for the current scanline
                   5814: 
                   5815:   Arguments:
                   5816:    $scantron_record - hash result from scantron_parse_scanline
                   5817:    $scan_data       - hash of correction information 
                   5818:                       (see &scantron_getfile() form more information)
                   5819:    $idmap           - hash from &username_to_idmap()
                   5820:    $line            - number of current scanline
                   5821:  
                   5822:   Returns:
                   5823:    Either 'username:domain' or undef if unknown
                   5824: 
1.423     albertel 5825: =cut
                   5826: 
1.82      albertel 5827: sub scantron_find_student {
1.157     albertel 5828:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5829:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5830:     if ($scanID =~ /^\s*$/) {
                   5831:  	return &scan_data($scan_data,"$line.user");
                   5832:     }
1.83      albertel 5833:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5834:  	if (lc($id) eq lc($scanID)) {
                   5835:  	    return $$idmap{$id};
                   5836:  	}
1.83      albertel 5837:     }
                   5838:     return undef;
                   5839: }
                   5840: 
1.423     albertel 5841: =pod
                   5842: 
                   5843: =item scantron_filter
                   5844: 
1.424     albertel 5845:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5846:    hidden resources was selected
                   5847: 
1.423     albertel 5848: =cut
                   5849: 
1.83      albertel 5850: sub scantron_filter {
                   5851:     my ($curres)=@_;
1.331     albertel 5852: 
                   5853:     if (ref($curres) && $curres->is_problem()) {
                   5854: 	# if the user has asked to not have either hidden
                   5855: 	# or 'randomout' controlled resources to be graded
                   5856: 	# don't include them
                   5857: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5858: 	    && $curres->randomout) {
                   5859: 	    return 0;
                   5860: 	}
1.83      albertel 5861: 	return 1;
                   5862:     }
                   5863:     return 0;
1.82      albertel 5864: }
                   5865: 
1.423     albertel 5866: =pod
                   5867: 
                   5868: =item scantron_process_corrections
                   5869: 
1.424     albertel 5870:    Gets correction information out of submitted form data and corrects
                   5871:    the scanline
                   5872: 
1.423     albertel 5873: =cut
                   5874: 
1.157     albertel 5875: sub scantron_process_corrections {
                   5876:     my ($r) = @_;
1.257     albertel 5877:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5878:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5879:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5880:     my $which=$env{'form.scantron_line'};
1.200     albertel 5881:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5882:     my ($skip,$err,$errmsg);
1.257     albertel 5883:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5884: 	$skip=1;
1.257     albertel 5885:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5886: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5887: 	    $env{'form.scantron_domain'};
1.157     albertel 5888: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5889: 	($line,$err,$errmsg)=
                   5890: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5891: 				     'ID',{'newid'=>$newid,
1.257     albertel 5892: 				    'username'=>$env{'form.scantron_username'},
                   5893: 				    'domain'=>$env{'form.scantron_domain'}});
                   5894:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5895: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5896: 	my $newCODE;
1.192     albertel 5897: 	my %args;
1.190     albertel 5898: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5899: 	    $newCODE='use_unfound';
1.190     albertel 5900: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5901: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5902: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5903: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5904: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5905: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5906: 	}
1.257     albertel 5907: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5908: 	    $args{'CODE_ignore_dup'}=1;
                   5909: 	}
                   5910: 	$args{'CODE'}=$newCODE;
1.186     albertel 5911: 	($line,$err,$errmsg)=
                   5912: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5913: 				     'CODE',\%args);
1.257     albertel 5914:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5915: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5916: 	    ($line,$err,$errmsg)=
                   5917: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5918: 					 $which,'answer',
                   5919: 					 { 'question'=>$question,
1.503     raeburn  5920: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   5921:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 5922: 	    if ($err) { last; }
                   5923: 	}
                   5924:     }
                   5925:     if ($err) {
1.398     albertel 5926: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5927:     } else {
1.200     albertel 5928: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5929: 	&scantron_putfile($scanlines,$scan_data);
                   5930:     }
                   5931: }
                   5932: 
1.423     albertel 5933: =pod
                   5934: 
                   5935: =item reset_skipping_status
                   5936: 
1.424     albertel 5937:    Forgets the current set of remember skipped scanlines (and thus
                   5938:    reverts back to considering all lines in the
                   5939:    scantron_skipped_<filename> file)
                   5940: 
1.423     albertel 5941: =cut
                   5942: 
1.200     albertel 5943: sub reset_skipping_status {
                   5944:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5945:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5946:     &scantron_putfile(undef,$scan_data);
                   5947: }
                   5948: 
1.423     albertel 5949: =pod
                   5950: 
                   5951: =item start_skipping
                   5952: 
1.424     albertel 5953:    Marks a scanline to be skipped. 
                   5954: 
1.423     albertel 5955: =cut
                   5956: 
1.376     albertel 5957: sub start_skipping {
1.200     albertel 5958:     my ($scan_data,$i)=@_;
                   5959:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5960:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5961: 	$remembered{$i}=2;
                   5962:     } else {
                   5963: 	$remembered{$i}=1;
                   5964:     }
1.200     albertel 5965:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5966: }
                   5967: 
1.423     albertel 5968: =pod
                   5969: 
                   5970: =item should_be_skipped
                   5971: 
1.424     albertel 5972:    Checks whether a scanline should be skipped.
                   5973: 
1.423     albertel 5974: =cut
                   5975: 
1.200     albertel 5976: sub should_be_skipped {
1.376     albertel 5977:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5978:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5979: 	# not redoing old skips
1.376     albertel 5980: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5981: 	return 0;
                   5982:     }
                   5983:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5984: 
                   5985:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5986: 	return 0;
                   5987:     }
1.200     albertel 5988:     return 1;
                   5989: }
                   5990: 
1.423     albertel 5991: =pod
                   5992: 
                   5993: =item remember_current_skipped
                   5994: 
1.424     albertel 5995:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5996:    file and remembers them into scan_data for later use.
                   5997: 
1.423     albertel 5998: =cut
                   5999: 
1.200     albertel 6000: sub remember_current_skipped {
                   6001:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6002:     my %to_remember;
                   6003:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6004: 	if ($scanlines->{'skipped'}[$i]) {
                   6005: 	    $to_remember{$i}=1;
                   6006: 	}
                   6007:     }
1.376     albertel 6008: 
1.200     albertel 6009:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6010:     &scantron_putfile(undef,$scan_data);
                   6011: }
                   6012: 
1.423     albertel 6013: =pod
                   6014: 
                   6015: =item check_for_error
                   6016: 
1.424     albertel 6017:     Checks if there was an error when attempting to remove a specific
                   6018:     scantron_.. bubble sheet data file. Prints out an error if
                   6019:     something went wrong.
                   6020: 
1.423     albertel 6021: =cut
                   6022: 
1.200     albertel 6023: sub check_for_error {
                   6024:     my ($r,$result)=@_;
                   6025:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6026: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6027:     }
                   6028: }
1.157     albertel 6029: 
1.423     albertel 6030: =pod
                   6031: 
                   6032: =item scantron_warning_screen
                   6033: 
1.424     albertel 6034:    Interstitial screen to make sure the operator has selected the
                   6035:    correct options before we start the validation phase.
                   6036: 
1.423     albertel 6037: =cut
                   6038: 
1.203     albertel 6039: sub scantron_warning_screen {
                   6040:     my ($button_text)=@_;
1.257     albertel 6041:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6042:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6043:     my $CODElist;
1.284     albertel 6044:     if ($scantron_config{'CODElocation'} &&
                   6045: 	$scantron_config{'CODEstart'} &&
                   6046: 	$scantron_config{'CODElength'}) {
                   6047: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6048: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6049: 	$CODElist=
1.492     albertel 6050: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6051: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6052:     }
1.492     albertel 6053:     return ('
1.203     albertel 6054: <p>
1.492     albertel 6055: <span class="LC_warning">
                   6056: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6057: </p>
                   6058: <table>
1.492     albertel 6059: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6060: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6061: '.$CODElist.'
1.203     albertel 6062: </table>
                   6063: <br />
1.492     albertel 6064: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6065: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6066: 
                   6067: <br />
1.492     albertel 6068: ');
1.203     albertel 6069: }
                   6070: 
1.423     albertel 6071: =pod
                   6072: 
                   6073: =item scantron_do_warning
                   6074: 
1.424     albertel 6075:    Check if the operator has picked something for all required
                   6076:    fields. Error out if something is missing.
                   6077: 
1.423     albertel 6078: =cut
                   6079: 
1.203     albertel 6080: sub scantron_do_warning {
                   6081:     my ($r)=@_;
1.324     albertel 6082:     my ($symb)=&get_symb($r);
1.203     albertel 6083:     if (!$symb) {return '';}
1.324     albertel 6084:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6085:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6086:     if ( $env{'form.selectpage'} eq '' ||
                   6087: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6088: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6089: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6090: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6091: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6092: 	} 
1.257     albertel 6093: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6094: 	    $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 6095: 	} 
1.257     albertel 6096: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6097: 	    $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 6098: 	} 
                   6099:     } else {
1.265     www      6100: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6101: 	$r->print('
                   6102: '.$warning.'
                   6103: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6104: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6105: ');
1.237     albertel 6106:     }
1.352     albertel 6107:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6108:     return '';
                   6109: }
                   6110: 
1.423     albertel 6111: =pod
                   6112: 
                   6113: =item scantron_form_start
                   6114: 
1.424     albertel 6115:     html hidden input for remembering all selected grading options
                   6116: 
1.423     albertel 6117: =cut
                   6118: 
1.203     albertel 6119: sub scantron_form_start {
                   6120:     my ($max_bubble)=@_;
                   6121:     my $result= <<SCANTRONFORM;
                   6122: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6123:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6124:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6125:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6126:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6127:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6128:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6129:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6130:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6131:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6132: SCANTRONFORM
1.447     foxr     6133: 
                   6134:   my $line = 0;
                   6135:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6136:        my $chunk =
                   6137: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6138:        $chunk .=
                   6139: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6140:        $chunk .= 
                   6141:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6142:        $chunk .=
                   6143:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6144:        $result .= $chunk;
                   6145:        $line++;
                   6146:    }
1.203     albertel 6147:     return $result;
                   6148: }
                   6149: 
1.423     albertel 6150: =pod
                   6151: 
                   6152: =item scantron_validate_file
                   6153: 
1.424     albertel 6154:     Dispatch routine for doing validation of a bubble sheet data file.
                   6155: 
                   6156:     Also processes any necessary information resets that need to
                   6157:     occur before validation begins (ignore previous corrections,
                   6158:     restarting the skipped records processing)
                   6159: 
1.423     albertel 6160: =cut
                   6161: 
1.157     albertel 6162: sub scantron_validate_file {
                   6163:     my ($r) = @_;
1.324     albertel 6164:     my ($symb)=&get_symb($r);
1.157     albertel 6165:     if (!$symb) {return '';}
1.324     albertel 6166:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6167:     
                   6168:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6169:     # them when doing the corrections reset
1.257     albertel 6170:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6171: 	&reset_skipping_status();
                   6172:     }
1.257     albertel 6173:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6174: 	&remember_current_skipped();
1.257     albertel 6175: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6176:     }
                   6177: 
1.257     albertel 6178:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6179: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6180: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6181: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6182: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6183:     }
1.200     albertel 6184: 
1.257     albertel 6185:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6186: 	&scantron_process_corrections($r);
                   6187:     }
1.503     raeburn  6188:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6189:     #get the student pick code ready
                   6190:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 6191:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 6192:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6193:     $r->print($result);
                   6194:     
1.334     albertel 6195:     my @validate_phases=( 'sequence',
                   6196: 			  'ID',
1.157     albertel 6197: 			  'CODE',
                   6198: 			  'doublebubble',
                   6199: 			  'missingbubbles');
1.257     albertel 6200:     if (!$env{'form.validatepass'}) {
                   6201: 	$env{'form.validatepass'} = 0;
1.157     albertel 6202:     }
1.257     albertel 6203:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6204: 
1.448     foxr     6205: 
1.157     albertel 6206:     my $stop=0;
                   6207:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6208: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6209: 	$r->rflush();
                   6210: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6211: 	{
                   6212: 	    no strict 'refs';
                   6213: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6214: 	}
                   6215:     }
                   6216:     if (!$stop) {
1.528.2.9  raeburn  6217:         my $warning=&scantron_warning_screen('Start Grading');
                   6218:         $r->print(&mt('Validation process complete.').'<br />'.
                   6219:                   $warning.
                   6220:                   &mt('Perform verification for each student after storage of submissions?').
                   6221:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6222:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6223:                   ('&nbsp;'x3).'<label>'.
                   6224:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6225:                   '</label></span><br />'.
                   6226:                   &mt('Grading will take longer if you use verification.').'<br />'.                  &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
                   6227:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6228:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6229:     } else {
1.528.2.9  raeburn  6230:         $r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6231:         $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
1.157     albertel 6232:     }
                   6233:     if ($stop) {
1.334     albertel 6234: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.528.2.11  raeburn  6235: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr;" />');
1.492     albertel 6236: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6237: 
1.492     albertel 6238: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6239: 	} else {
1.503     raeburn  6240:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.528.2.11  raeburn  6241: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6242:             } else {
1.528.2.11  raeburn  6243:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6244:             }
1.492     albertel 6245: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6246: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6247: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6248: 	}
1.157     albertel 6249:     }
1.352     albertel 6250:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6251:     return '';
                   6252: }
                   6253: 
1.423     albertel 6254: 
                   6255: =pod
                   6256: 
                   6257: =item scantron_remove_file
                   6258: 
1.424     albertel 6259:    Removes the requested bubble sheet data file, makes sure that
                   6260:    scantron_original_<filename> is never removed
                   6261: 
                   6262: 
1.423     albertel 6263: =cut
                   6264: 
1.200     albertel 6265: sub scantron_remove_file {
1.192     albertel 6266:     my ($which)=@_;
1.257     albertel 6267:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6268:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6269:     my $file='scantron_';
1.200     albertel 6270:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6271: 	$file.=$which.'_';
1.192     albertel 6272:     } else {
                   6273: 	return 'refused';
                   6274:     }
1.257     albertel 6275:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6276:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6277: }
                   6278: 
1.423     albertel 6279: 
                   6280: =pod
                   6281: 
                   6282: =item scantron_remove_scan_data
                   6283: 
1.424     albertel 6284:    Removes all scan_data correction for the requested bubble sheet
                   6285:    data file.  (In the case that both the are doing skipped records we need
                   6286:    to remember the old skipped lines for the time being so that element
                   6287:    persists for a while.)
                   6288: 
1.423     albertel 6289: =cut
                   6290: 
1.200     albertel 6291: sub scantron_remove_scan_data {
1.257     albertel 6292:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6293:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6294:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6295:     my @todelete;
1.257     albertel 6296:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6297:     foreach my $key (@keys) {
                   6298: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6299: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6300: 		$key=~/remember_skipping/) {
                   6301: 		next;
                   6302: 	    }
1.192     albertel 6303: 	    push(@todelete,$key);
                   6304: 	}
                   6305:     }
1.200     albertel 6306:     my $result;
1.192     albertel 6307:     if (@todelete) {
1.491     albertel 6308: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6309: 				       \@todelete,$cdom,$cname);
                   6310:     } else {
                   6311: 	$result = 'ok';
1.192     albertel 6312:     }
                   6313:     return $result;
                   6314: }
                   6315: 
1.423     albertel 6316: 
                   6317: =pod
                   6318: 
                   6319: =item scantron_getfile
                   6320: 
1.424     albertel 6321:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6322:     the scan_data hash
                   6323:   
                   6324:   Arguments:
                   6325:     None
                   6326: 
                   6327:   Returns:
                   6328:     2 hash references
                   6329: 
                   6330:      - first one has 
                   6331:          orig      -
                   6332:          corrected -
                   6333:          skipped   -  each of which points to an array ref of the specified
                   6334:                       file broken up into individual lines
                   6335:          count     - number of scanlines
                   6336:  
                   6337:      - second is the scan_data hash possible keys are
1.425     albertel 6338:        ($number refers to scanline numbered $number and thus the key affects
                   6339:         only that scanline
                   6340:         $bubline refers to the specific bubble line element and the aspects
                   6341:         refers to that specific bubble line element)
                   6342: 
                   6343:        $number.user - username:domain to use
                   6344:        $number.CODE_ignore_dup 
                   6345:                     - ignore the duplicate CODE error 
                   6346:        $number.useCODE
                   6347:                     - use the CODE in the scanline as is
                   6348:        $number.no_bubble.$bubline
                   6349:                     - it is valid that there is no bubbled in bubble
                   6350:                       at $number $bubline
                   6351:        remember_skipping
                   6352:                     - a frozen hash containing keys of $number and values
                   6353:                       of either 
                   6354:                         1 - we are on a 'do skipped records pass' and plan
                   6355:                             on processing this line
                   6356:                         2 - we are on a 'do skipped records pass' and this
                   6357:                             scanline has been marked to skip yet again
1.424     albertel 6358: 
1.423     albertel 6359: =cut
                   6360: 
1.157     albertel 6361: sub scantron_getfile {
1.200     albertel 6362:     #FIXME really would prefer a scantron directory
1.257     albertel 6363:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6364:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6365:     my $lines;
                   6366:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6367: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6368:     my %scanlines;
                   6369:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6370:     my $temp=$scanlines{'orig'};
                   6371:     $scanlines{'count'}=$#$temp;
                   6372: 
                   6373:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6374: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6375:     if ($lines eq '-1') {
                   6376: 	$scanlines{'corrected'}=[];
                   6377:     } else {
                   6378: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6379:     }
                   6380:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6381: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6382:     if ($lines eq '-1') {
                   6383: 	$scanlines{'skipped'}=[];
                   6384:     } else {
                   6385: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6386:     }
1.175     albertel 6387:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6388:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6389:     my %scan_data = @tmp;
                   6390:     return (\%scanlines,\%scan_data);
                   6391: }
                   6392: 
1.423     albertel 6393: =pod
                   6394: 
                   6395: =item lonnet_putfile
                   6396: 
1.424     albertel 6397:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6398: 
                   6399:  Arguments:
                   6400:    $contents - data to store
                   6401:    $filename - filename to store $contents into
                   6402: 
                   6403:  Returns:
                   6404:    result value from &Apache::lonnet::finishuserfileupload
                   6405: 
1.423     albertel 6406: =cut
                   6407: 
1.157     albertel 6408: sub lonnet_putfile {
                   6409:     my ($contents,$filename)=@_;
1.257     albertel 6410:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6411:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6412:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6413:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6414: 
                   6415: }
                   6416: 
1.423     albertel 6417: =pod
                   6418: 
                   6419: =item scantron_putfile
                   6420: 
1.424     albertel 6421:     Stores the current version of the bubble sheet data files, and the
                   6422:     scan_data hash. (Does not modify the original version only the
                   6423:     corrected and skipped versions.
                   6424: 
                   6425:  Arguments:
                   6426:     $scanlines - hash ref that looks like the first return value from
                   6427:                  &scantron_getfile()
                   6428:     $scan_data - hash ref that looks like the second return value from
                   6429:                  &scantron_getfile()
                   6430: 
1.423     albertel 6431: =cut
                   6432: 
1.157     albertel 6433: sub scantron_putfile {
                   6434:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6435:     #FIXME really would prefer a scantron directory
1.257     albertel 6436:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6437:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6438:     if ($scanlines) {
                   6439: 	my $prefix='scantron_';
1.157     albertel 6440: # no need to update orig, shouldn't change
                   6441: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6442: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6443: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6444: 			$prefix.'corrected_'.
1.257     albertel 6445: 			$env{'form.scantron_selectfile'});
1.200     albertel 6446: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6447: 			$prefix.'skipped_'.
1.257     albertel 6448: 			$env{'form.scantron_selectfile'});
1.200     albertel 6449:     }
1.175     albertel 6450:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6451: }
                   6452: 
1.423     albertel 6453: =pod
                   6454: 
                   6455: =item scantron_get_line
                   6456: 
1.424     albertel 6457:    Returns the correct version of the scanline
                   6458: 
                   6459:  Arguments:
                   6460:     $scanlines - hash ref that looks like the first return value from
                   6461:                  &scantron_getfile()
                   6462:     $scan_data - hash ref that looks like the second return value from
                   6463:                  &scantron_getfile()
                   6464:     $i         - number of the requested line (starts at 0)
                   6465: 
                   6466:  Returns:
                   6467:    A scanline, (either the original or the corrected one if it
                   6468:    exists), or undef if the requested scanline should be
                   6469:    skipped. (Either because it's an skipped scanline, or it's an
                   6470:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6471:    pass.
                   6472: 
1.423     albertel 6473: =cut
                   6474: 
1.157     albertel 6475: sub scantron_get_line {
1.200     albertel 6476:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6477:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6478:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6479:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6480:     return $scanlines->{'orig'}[$i]; 
                   6481: }
                   6482: 
1.423     albertel 6483: =pod
                   6484: 
                   6485: =item scantron_todo_count
                   6486: 
1.424     albertel 6487:     Counts the number of scanlines that need processing.
                   6488: 
                   6489:  Arguments:
                   6490:     $scanlines - hash ref that looks like the first return value from
                   6491:                  &scantron_getfile()
                   6492:     $scan_data - hash ref that looks like the second return value from
                   6493:                  &scantron_getfile()
                   6494: 
                   6495:  Returns:
                   6496:     $count - number of scanlines to process
                   6497: 
1.423     albertel 6498: =cut
                   6499: 
1.200     albertel 6500: sub get_todo_count {
                   6501:     my ($scanlines,$scan_data)=@_;
                   6502:     my $count=0;
                   6503:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6504: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6505: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6506: 	$count++;
                   6507:     }
                   6508:     return $count;
                   6509: }
                   6510: 
1.423     albertel 6511: =pod
                   6512: 
                   6513: =item scantron_put_line
                   6514: 
1.424     albertel 6515:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6516:     data file.
                   6517: 
                   6518:  Arguments:
                   6519:     $scanlines - hash ref that looks like the first return value from
                   6520:                  &scantron_getfile()
                   6521:     $scan_data - hash ref that looks like the second return value from
                   6522:                  &scantron_getfile()
                   6523:     $i         - line number to update
                   6524:     $newline   - contents of the updated scanline
                   6525:     $skip      - if true make the line for skipping and update the
                   6526:                  'skipped' file
                   6527: 
1.423     albertel 6528: =cut
                   6529: 
1.157     albertel 6530: sub scantron_put_line {
1.200     albertel 6531:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6532:     if ($skip) {
                   6533: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6534: 	&start_skipping($scan_data,$i);
1.157     albertel 6535: 	return;
                   6536:     }
                   6537:     $scanlines->{'corrected'}[$i]=$newline;
                   6538: }
                   6539: 
1.423     albertel 6540: =pod
                   6541: 
                   6542: =item scantron_clear_skip
                   6543: 
1.424     albertel 6544:    Remove a line from the 'skipped' file
                   6545: 
                   6546:  Arguments:
                   6547:     $scanlines - hash ref that looks like the first return value from
                   6548:                  &scantron_getfile()
                   6549:     $scan_data - hash ref that looks like the second return value from
                   6550:                  &scantron_getfile()
                   6551:     $i         - line number to update
                   6552: 
1.423     albertel 6553: =cut
                   6554: 
1.376     albertel 6555: sub scantron_clear_skip {
                   6556:     my ($scanlines,$scan_data,$i)=@_;
                   6557:     if (exists($scanlines->{'skipped'}[$i])) {
                   6558: 	undef($scanlines->{'skipped'}[$i]);
                   6559: 	return 1;
                   6560:     }
                   6561:     return 0;
                   6562: }
                   6563: 
1.423     albertel 6564: =pod
                   6565: 
                   6566: =item scantron_filter_not_exam
                   6567: 
1.424     albertel 6568:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6569:    filter out resources that are not marked as 'exam' mode
                   6570: 
1.423     albertel 6571: =cut
                   6572: 
1.334     albertel 6573: sub scantron_filter_not_exam {
                   6574:     my ($curres)=@_;
                   6575:     
                   6576:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6577: 	# if the user has asked to not have either hidden
                   6578: 	# or 'randomout' controlled resources to be graded
                   6579: 	# don't include them
                   6580: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6581: 	    && $curres->randomout) {
                   6582: 	    return 0;
                   6583: 	}
                   6584: 	return 1;
                   6585:     }
                   6586:     return 0;
                   6587: }
                   6588: 
1.423     albertel 6589: =pod
                   6590: 
                   6591: =item scantron_validate_sequence
                   6592: 
1.424     albertel 6593:     Validates the selected sequence, checking for resource that are
                   6594:     not set to exam mode.
                   6595: 
1.423     albertel 6596: =cut
                   6597: 
1.334     albertel 6598: sub scantron_validate_sequence {
                   6599:     my ($r,$currentphase) = @_;
                   6600: 
                   6601:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6602:     my (undef,undef,$sequence)=
                   6603: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6604: 
                   6605:     my $map=$navmap->getResourceByUrl($sequence);
                   6606: 
                   6607:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6608:                                     value="ignore" />');
                   6609:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6610: 	my @resources=
                   6611: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6612: 	if (@resources) {
1.357     banghart 6613: 	    $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 6614: 	    return (1,$currentphase);
                   6615: 	}
                   6616:     }
                   6617: 
                   6618:     return (0,$currentphase+1);
                   6619: }
                   6620: 
1.423     albertel 6621: =pod
                   6622: 
                   6623: =item scantron_validate_ID
                   6624: 
1.424     albertel 6625:    Validates all scanlines in the selected file to not have any
                   6626:    invalid or underspecified student IDs
                   6627: 
1.423     albertel 6628: =cut
                   6629: 
1.157     albertel 6630: sub scantron_validate_ID {
                   6631:     my ($r,$currentphase) = @_;
                   6632:     
                   6633:     #get student info
                   6634:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6635:     my %idmap=&username_to_idmap($classlist);
                   6636: 
                   6637:     #get scantron line setup
1.257     albertel 6638:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6639:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6640:     
                   6641:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6642: 
                   6643:     my %found=('ids'=>{},'usernames'=>{});
                   6644:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6645: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6646: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6647: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6648: 						 $scan_data);
                   6649: 	my $id=$$scan_record{'scantron.ID'};
                   6650: 	my $found;
                   6651: 	foreach my $checkid (keys(%idmap)) {
                   6652: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6653: 	}
                   6654: 	if ($found) {
                   6655: 	    my $username=$idmap{$found};
                   6656: 	    if ($found{'ids'}{$found}) {
                   6657: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6658: 					 $line,'duplicateID',$found);
1.194     albertel 6659: 		return(1,$currentphase);
1.157     albertel 6660: 	    } elsif ($found{'usernames'}{$username}) {
                   6661: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6662: 					 $line,'duplicateID',$username);
1.194     albertel 6663: 		return(1,$currentphase);
1.157     albertel 6664: 	    }
1.186     albertel 6665: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6666: 	    $found{'ids'}{$found}++;
                   6667: 	    $found{'usernames'}{$username}++;
                   6668: 	} else {
                   6669: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6670: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6671: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6672: 		    &scantron_get_correction($r,$i,$scan_record,
                   6673: 					     \%scantron_config,
                   6674: 					     $line,'duplicateID',$username);
1.194     albertel 6675: 		    return(1,$currentphase);
1.157     albertel 6676: 		} elsif (!defined($username)) {
                   6677: 		    &scantron_get_correction($r,$i,$scan_record,
                   6678: 					     \%scantron_config,
                   6679: 					     $line,'incorrectID');
1.194     albertel 6680: 		    return(1,$currentphase);
1.157     albertel 6681: 		}
                   6682: 		$found{'usernames'}{$username}++;
                   6683: 	    } else {
                   6684: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6685: 					 $line,'incorrectID');
1.194     albertel 6686: 		return(1,$currentphase);
1.157     albertel 6687: 	    }
                   6688: 	}
                   6689:     }
                   6690: 
                   6691:     return (0,$currentphase+1);
                   6692: }
                   6693: 
1.423     albertel 6694: =pod
                   6695: 
                   6696: =item scantron_get_correction
                   6697: 
1.424     albertel 6698:    Builds the interface screen to interact with the operator to fix a
                   6699:    specific error condition in a specific scanline
                   6700: 
                   6701:  Arguments:
                   6702:     $r           - Apache request object
                   6703:     $i           - number of the current scanline
                   6704:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6705:     $scan_config - hash ref as returned from &get_scantron_config()
                   6706:     $line        - full contents of the current scanline
                   6707:     $error       - error condition, valid values are
                   6708:                    'incorrectCODE', 'duplicateCODE',
                   6709:                    'doublebubble', 'missingbubble',
                   6710:                    'duplicateID', 'incorrectID'
                   6711:     $arg         - extra information needed
                   6712:        For errors:
                   6713:          - duplicateID   - paper number that this studentID was seen before on
                   6714:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6715:                            seen on before
                   6716:          - incorrectCODE - current incorrect CODE 
                   6717:          - doublebubble  - array ref of the bubble lines that have double
                   6718:                            bubble errors
                   6719:          - missingbubble - array ref of the bubble lines that have missing
                   6720:                            bubble errors
                   6721: 
1.423     albertel 6722: =cut
                   6723: 
1.157     albertel 6724: sub scantron_get_correction {
                   6725:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6726: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6727: #to show both the current line and the previous one and allow skipping
                   6728: #the previous one or the current one
                   6729: 
1.333     albertel 6730:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6731: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6732: 			    " for PaperID <tt>[_1]</tt>",
                   6733: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6734:     } else {
1.492     albertel 6735: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6736: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6737: 			    $i,$line)."</p> \n");
                   6738:     }
                   6739:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6740: 			  "The name on the paper is [_2],[_3]",
                   6741: 			  $$scan_record{'scantron.ID'},
                   6742: 			  $$scan_record{'scantron.LastName'},
                   6743: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6744: 
1.157     albertel 6745:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6746:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6747:                            # Array populated for doublebubble or
                   6748:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6749:                            # to validate radio button checking   
                   6750: 
1.157     albertel 6751:     if ($error =~ /ID$/) {
1.186     albertel 6752: 	if ($error eq 'incorrectID') {
1.492     albertel 6753: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6754: 		      "</p>\n");
1.157     albertel 6755: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6756: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6757: 	}
1.242     albertel 6758: 	$r->print($message);
1.492     albertel 6759: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6760: 	$r->print("\n<ul><li> ");
                   6761: 	#FIXME it would be nice if this sent back the user ID and
                   6762: 	#could do partial userID matches
                   6763: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6764: 				       'scantron_username','scantron_domain'));
                   6765: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6766: 	$r->print("\n@".
1.257     albertel 6767: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6768: 
                   6769: 	$r->print('</li>');
1.186     albertel 6770:     } elsif ($error =~ /CODE$/) {
                   6771: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6772: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6773: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6774: 	    $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 6775: 	}
1.492     albertel 6776: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6777: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6778: 	$r->print($message);
1.492     albertel 6779: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6780: 	$r->print("\n<br /> ");
1.194     albertel 6781: 	my $i=0;
1.273     albertel 6782: 	if ($error eq 'incorrectCODE' 
                   6783: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6784: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6785: 	    if ($closest > 0) {
                   6786: 		foreach my $testcode (@{$closest}) {
                   6787: 		    my $checked='';
1.401     albertel 6788: 		    if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6789: 		    $r->print("
                   6790:    <label>
                   6791:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
                   6792:        ".&mt("Use the similar CODE [_1] instead.",
                   6793: 	    "<b><tt>".$testcode."</tt></b>")."
                   6794:     </label>
                   6795:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6796: 		    $r->print("\n<br />");
                   6797: 		    $i++;
                   6798: 		}
1.194     albertel 6799: 	    }
                   6800: 	}
1.273     albertel 6801: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6802: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6803: 	    $r->print("
                   6804:     <label>
                   6805:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
                   6806:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6807: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6808:     </label>");
1.273     albertel 6809: 	    $r->print("\n<br />");
                   6810: 	}
1.194     albertel 6811: 
1.188     albertel 6812: 	$r->print(<<ENDSCRIPT);
                   6813: <script type="text/javascript">
                   6814: function change_radio(field) {
1.190     albertel 6815:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6816:     var i;
                   6817:     for (i=0;i<slct.length;i++) {
                   6818:         if (slct[i].value==field) { slct[i].checked=true; }
                   6819:     }
                   6820: }
                   6821: </script>
                   6822: ENDSCRIPT
1.187     albertel 6823: 	my $href="/adm/pickcode?".
1.359     www      6824: 	   "form=".&escape("scantronupload").
                   6825: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6826: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6827: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6828: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6829: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6830: 	    $r->print("
                   6831:     <label>
                   6832:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6833:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6834: 	     "<a target='_blank' href='$href'>","</a>")."
                   6835:     </label> 
1.528.2.12! raeburn  6836:     ".&mt('Selected CODE is [_1]','<input readonly="readonly" type="text" size="8" name="scantron_CODE_selectedvalue" onfocus="javascript:change_radio(\'use_found\')" onchange="javascript:change_radio(\'use_found\')" />'));
1.332     albertel 6837: 	    $r->print("\n<br />");
                   6838: 	}
1.492     albertel 6839: 	$r->print("
                   6840:     <label>
                   6841:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6842:        ".&mt("Use [_1] as the CODE.",
                   6843: 	     "</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 6844: 	$r->print("\n<br /><br />");
1.157     albertel 6845:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6846: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6847: 
                   6848: 	# The form field scantron_questions is acutally a list of line numbers.
                   6849: 	# represented by this form so:
                   6850: 
                   6851: 	my $line_list = &questions_to_line_list($arg);
                   6852: 
1.157     albertel 6853: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6854: 		  $line_list.'" />');
1.242     albertel 6855: 	$r->print($message);
1.492     albertel 6856: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6857: 	foreach my $question (@{$arg}) {
1.503     raeburn  6858: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6859:                                                    $scan_record, $error);
1.524     raeburn  6860:             push(@lines_to_correct,@linenums);
1.157     albertel 6861: 	}
1.503     raeburn  6862:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6863:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6864: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6865: 	$r->print($message);
1.492     albertel 6866: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6867: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6868: 
1.503     raeburn  6869: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6870: 	# a list of question numbers. Therefore:
                   6871: 	#
                   6872: 	
                   6873: 	my $line_list = &questions_to_line_list($arg);
                   6874: 
1.157     albertel 6875: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6876: 		  $line_list.'" />');
1.157     albertel 6877: 	foreach my $question (@{$arg}) {
1.503     raeburn  6878: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6879:                                                    $scan_record, $error);
1.524     raeburn  6880:             push(@lines_to_correct,@linenums);
1.157     albertel 6881: 	}
1.503     raeburn  6882:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6883:     } else {
                   6884: 	$r->print("\n<ul>");
                   6885:     }
                   6886:     $r->print("\n</li></ul>");
1.497     foxr     6887: }
                   6888: 
1.503     raeburn  6889: sub verify_bubbles_checked {
                   6890:     my (@ansnums) = @_;
                   6891:     my $ansnumstr = join('","',@ansnums);
                   6892:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6893:     my $output = (<<ENDSCRIPT);
                   6894: <script type="text/javascript">
                   6895: function verify_bubble_radio(form) {
                   6896:     var ansnumArray = new Array ("$ansnumstr");
                   6897:     var need_bubble_count = 0;
                   6898:     for (var i=0; i<ansnumArray.length; i++) {
                   6899:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6900:             var bubble_picked = 0; 
                   6901:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6902:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6903:                     bubble_picked = 1;
                   6904:                 }
                   6905:             }
                   6906:             if (bubble_picked == 0) {
                   6907:                 need_bubble_count ++;
                   6908:             }
                   6909:         }
                   6910:     }
                   6911:     if (need_bubble_count) {
                   6912:         alert("$warning");
                   6913:         return;
                   6914:     }
                   6915:     form.submit(); 
                   6916: }
                   6917: </script>
                   6918: ENDSCRIPT
                   6919:     return $output;
                   6920: }
                   6921: 
1.497     foxr     6922: =pod
                   6923: 
                   6924: =item  questions_to_line_list
1.157     albertel 6925: 
1.497     foxr     6926: Converts a list of questions into a string of comma separated
                   6927: line numbers in the answer sheet used by the questions.  This is
                   6928: used to fill in the scantron_questions form field.
                   6929: 
                   6930:   Arguments:
                   6931:      questions    - Reference to an array of questions.
                   6932: 
                   6933: =cut
                   6934: 
                   6935: 
                   6936: sub questions_to_line_list {
                   6937:     my ($questions) = @_;
                   6938:     my @lines;
                   6939: 
1.503     raeburn  6940:     foreach my $item (@{$questions}) {
                   6941:         my $question = $item;
                   6942:         my ($first,$count,$last);
                   6943:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   6944:             $question = $1;
                   6945:             my $subquestion = $2;
                   6946:             $first = $first_bubble_line{$question-1} + 1;
                   6947:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6948:             my $subcount = 1;
                   6949:             while ($subcount<$subquestion) {
                   6950:                 $first += $subans[$subcount-1];
                   6951:                 $subcount ++;
                   6952:             }
                   6953:             $count = $subans[$subquestion-1];
                   6954:         } else {
                   6955: 	    $first   = $first_bubble_line{$question-1} + 1;
                   6956: 	    $count   = $bubble_lines_per_response{$question-1};
                   6957:         }
1.506     raeburn  6958:         $last = $first+$count-1;
1.503     raeburn  6959:         push(@lines, ($first..$last));
1.497     foxr     6960:     }
                   6961:     return join(',', @lines);
                   6962: }
                   6963: 
                   6964: =pod 
                   6965: 
                   6966: =item prompt_for_corrections
                   6967: 
                   6968: Prompts for a potentially multiline correction to the
                   6969: user's bubbling (factors out common code from scantron_get_correction
                   6970: for multi and missing bubble cases).
                   6971: 
                   6972:  Arguments:
                   6973:    $r           - Apache request object.
                   6974:    $question    - The question number to prompt for.
                   6975:    $scan_config - The scantron file configuration hash.
                   6976:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  6977:    $error       - Type of error
1.497     foxr     6978: 
                   6979:  Implicit inputs:
                   6980:    %bubble_lines_per_response   - Starting line numbers for each question.
                   6981:                                   Numbered from 0 (but question numbers are from
                   6982:                                   1.
                   6983:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  6984:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   6985:                                   type problems render as separate sub-questions, 
1.503     raeburn  6986:                                   in exam mode. This hash contains a 
                   6987:                                   comma-separated list of the lines per 
                   6988:                                   sub-question.
1.510     raeburn  6989:    %responsetype_per_response   - essayresponse, formularesponse,
                   6990:                                   stringresponse, imageresponse, reactionresponse,
                   6991:                                   and organicresponse type problem parts can have
1.503     raeburn  6992:                                   multiple lines per response if the weight
                   6993:                                   assigned exceeds 10.  In this case, only
                   6994:                                   one bubble per line is permitted, but more 
                   6995:                                   than one line might contain bubbles, e.g.
                   6996:                                   bubbling of: line 1 - J, line 2 - J, 
                   6997:                                   line 3 - B would assign 22 points.  
1.497     foxr     6998: 
                   6999: =cut
                   7000: 
                   7001: sub prompt_for_corrections {
1.503     raeburn  7002:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7003:     my ($current_line,$lines);
                   7004:     my @linenums;
                   7005:     my $questionnum = $question;
                   7006:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7007:         $question = $1;
                   7008:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7009:         my $subquestion = $2;
                   7010:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7011:         my $subcount = 1;
                   7012:         while ($subcount<$subquestion) {
                   7013:             $current_line += $subans[$subcount-1];
                   7014:             $subcount ++;
                   7015:         }
                   7016:         $lines = $subans[$subquestion-1];
                   7017:     } else {
                   7018:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7019:         $lines        = $bubble_lines_per_response{$question-1};
                   7020:     }
1.497     foxr     7021:     if ($lines > 1) {
1.503     raeburn  7022:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7023:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7024:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7025:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7026:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7027:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7028:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.503     raeburn  7029:             $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 />');
                   7030:         } else {
                   7031:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7032:         }
1.497     foxr     7033:     }
                   7034:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7035:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7036: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7037: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7038:         push(@linenums,$current_line);
1.497     foxr     7039: 	$current_line++;
                   7040:     }
                   7041:     if ($lines > 1) {
                   7042: 	$r->print("<hr /><br />");
                   7043:     }
1.503     raeburn  7044:     return @linenums;
1.157     albertel 7045: }
1.423     albertel 7046: 
                   7047: =pod
                   7048: 
                   7049: =item scantron_bubble_selector
                   7050:   
                   7051:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7052:    possibly showing the existing the selected bubbles if known
1.423     albertel 7053: 
                   7054:  Arguments:
                   7055:     $r           - Apache request object
                   7056:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7057:     $line        - Number of the line being displayed.
1.503     raeburn  7058:     $questionnum - Question number (may include subquestion)
                   7059:     $error       - Type of error.
1.497     foxr     7060:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7061: 
                   7062: =cut
                   7063: 
1.157     albertel 7064: sub scantron_bubble_selector {
1.503     raeburn  7065:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7066:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7067: 
                   7068:     my $scmode=$$scan_config{'Qon'};
                   7069:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7070: 
1.157     albertel 7071:     my @alphabet=('A'..'Z');
1.503     raeburn  7072:     $r->print(&Apache::loncommon::start_data_table().
                   7073:               &Apache::loncommon::start_data_table_row());
                   7074:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7075:     for (my $i=0;$i<$max+1;$i++) {
                   7076: 	$r->print("\n".'<td align="center">');
                   7077: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7078: 	else { $r->print('&nbsp;'); }
                   7079: 	$r->print('</td>');
                   7080:     }
1.503     raeburn  7081:     $r->print(&Apache::loncommon::end_data_table_row().
                   7082:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7083:     for (my $i=0;$i<$max;$i++) {
                   7084: 	$r->print("\n".
                   7085: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7086: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7087:     }
1.503     raeburn  7088:     my $nobub_checked = ' ';
                   7089:     if ($error eq 'missingbubble') {
                   7090:         $nobub_checked = ' checked = "checked" ';
                   7091:     }
                   7092:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7093: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7094:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7095:               $line.'" value="'.$questionnum.'" /></td>');
                   7096:     $r->print(&Apache::loncommon::end_data_table_row().
                   7097:               &Apache::loncommon::end_data_table());
1.157     albertel 7098: }
                   7099: 
1.423     albertel 7100: =pod
                   7101: 
                   7102: =item num_matches
                   7103: 
1.424     albertel 7104:    Counts the number of characters that are the same between the two arguments.
                   7105: 
                   7106:  Arguments:
                   7107:    $orig - CODE from the scanline
                   7108:    $code - CODE to match against
                   7109: 
                   7110:  Returns:
                   7111:    $count - integer count of the number of same characters between the
                   7112:             two arguments
                   7113: 
1.423     albertel 7114: =cut
                   7115: 
1.194     albertel 7116: sub num_matches {
                   7117:     my ($orig,$code) = @_;
                   7118:     my @code=split(//,$code);
                   7119:     my @orig=split(//,$orig);
                   7120:     my $same=0;
                   7121:     for (my $i=0;$i<scalar(@code);$i++) {
                   7122: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7123:     }
                   7124:     return $same;
                   7125: }
                   7126: 
1.423     albertel 7127: =pod
                   7128: 
                   7129: =item scantron_get_closely_matching_CODEs
                   7130: 
1.424     albertel 7131:    Cycles through all CODEs and finds the set that has the greatest
                   7132:    number of same characters as the provided CODE
                   7133: 
                   7134:  Arguments:
                   7135:    $allcodes - hash ref returned by &get_codes()
                   7136:    $CODE     - CODE from the current scanline
                   7137: 
                   7138:  Returns:
                   7139:    2 element list
                   7140:     - first elements is number of how closely matching the best fit is 
                   7141:       (5 means best set has 5 matching characters)
                   7142:     - second element is an arrary ref containing the set of valid CODEs
                   7143:       that best fit the passed in CODE
                   7144: 
1.423     albertel 7145: =cut
                   7146: 
1.194     albertel 7147: sub scantron_get_closely_matching_CODEs {
                   7148:     my ($allcodes,$CODE)=@_;
                   7149:     my @CODEs;
                   7150:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7151: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7152:     }
                   7153: 
                   7154:     return ($#CODEs,$CODEs[-1]);
                   7155: }
                   7156: 
1.423     albertel 7157: =pod
                   7158: 
                   7159: =item get_codes
                   7160: 
1.424     albertel 7161:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7162:    set of remembered CODEs.
                   7163: 
                   7164:  Arguments:
                   7165:   $old_name - name of the set of remembered CODEs
                   7166:   $cdom     - domain of the course
                   7167:   $cnum     - internal course name
                   7168: 
                   7169:  Returns:
                   7170:   %allcodes - keys are the valid CODEs, values are all 1
                   7171: 
1.423     albertel 7172: =cut
                   7173: 
1.194     albertel 7174: sub get_codes {
1.280     foxr     7175:     my ($old_name, $cdom, $cnum) = @_;
                   7176:     if (!$old_name) {
                   7177: 	$old_name=$env{'form.scantron_CODElist'};
                   7178:     }
                   7179:     if (!$cdom) {
                   7180: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7181:     }
                   7182:     if (!$cnum) {
                   7183: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7184:     }
1.278     albertel 7185:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7186: 				    $cdom,$cnum);
                   7187:     my %allcodes;
                   7188:     if ($result{"type\0$old_name"} eq 'number') {
                   7189: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7190:     } else {
                   7191: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7192:     }
1.194     albertel 7193:     return %allcodes;
                   7194: }
                   7195: 
1.423     albertel 7196: =pod
                   7197: 
                   7198: =item scantron_validate_CODE
                   7199: 
1.424     albertel 7200:    Validates all scanlines in the selected file to not have any
                   7201:    invalid or underspecified CODEs and that none of the codes are
                   7202:    duplicated if this was requested.
                   7203: 
1.423     albertel 7204: =cut
                   7205: 
1.157     albertel 7206: sub scantron_validate_CODE {
                   7207:     my ($r,$currentphase) = @_;
1.257     albertel 7208:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7209:     if ($scantron_config{'CODElocation'} &&
                   7210: 	$scantron_config{'CODEstart'} &&
                   7211: 	$scantron_config{'CODElength'}) {
1.257     albertel 7212: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7213: 	    &FIXME_blow_up()
                   7214: 	}
                   7215:     } else {
                   7216: 	return (0,$currentphase+1);
                   7217:     }
                   7218:     
                   7219:     my %usedCODEs;
                   7220: 
1.194     albertel 7221:     my %allcodes=&get_codes();
1.186     albertel 7222: 
1.447     foxr     7223:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   7224: 
1.186     albertel 7225:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7226:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7227: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7228: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7229: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7230: 						 $scan_data);
                   7231: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7232: 	my $error=0;
1.224     albertel 7233: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7234: 	    &scantron_get_correction($r,$i,$scan_record,
                   7235: 				     \%scantron_config,
                   7236: 				     $line,'incorrectCODE',\%allcodes);
                   7237: 	    return(1,$currentphase);
                   7238: 	}
1.221     albertel 7239: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7240: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7241: 	    &scantron_get_correction($r,$i,$scan_record,
                   7242: 				     \%scantron_config,
1.194     albertel 7243: 				     $line,'incorrectCODE',\%allcodes);
                   7244: 	    return(1,$currentphase);
1.186     albertel 7245: 	}
1.214     albertel 7246: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7247: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7248: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7249: 	    &scantron_get_correction($r,$i,$scan_record,
                   7250: 				     \%scantron_config,
1.194     albertel 7251: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7252: 	    return(1,$currentphase);
1.186     albertel 7253: 	}
1.524     raeburn  7254: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7255:     }
1.157     albertel 7256:     return (0,$currentphase+1);
                   7257: }
                   7258: 
1.423     albertel 7259: =pod
                   7260: 
                   7261: =item scantron_validate_doublebubble
                   7262: 
1.424     albertel 7263:    Validates all scanlines in the selected file to not have any
                   7264:    bubble lines with multiple bubbles marked.
                   7265: 
1.423     albertel 7266: =cut
                   7267: 
1.157     albertel 7268: sub scantron_validate_doublebubble {
                   7269:     my ($r,$currentphase) = @_;
                   7270:     #get student info
                   7271:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7272:     my %idmap=&username_to_idmap($classlist);
                   7273: 
                   7274:     #get scantron line setup
1.257     albertel 7275:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7276:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     7277:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   7278: 
1.157     albertel 7279:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7280: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7281: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7282: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7283: 						 $scan_data);
                   7284: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7285: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7286: 				 'doublebubble',
                   7287: 				 $$scan_record{'scantron.doubleerror'});
                   7288:     	return (1,$currentphase);
                   7289:     }
                   7290:     return (0,$currentphase+1);
                   7291: }
                   7292: 
1.423     albertel 7293: =pod
                   7294: 
                   7295: =item scantron_get_maxbubble
                   7296: 
1.424     albertel 7297:    Returns the maximum number of bubble lines that are expected to
                   7298:    occur. Does this by walking the selected sequence rendering the
                   7299:    resource and then checking &Apache::lonxml::get_problem_counter()
                   7300:    for what the current value of the problem counter is.
                   7301: 
1.447     foxr     7302:    Caches the results to $env{'form.scantron_maxbubble'},
1.503     raeburn  7303:    $env{'form.scantron.bubble_lines.n'}, 
                   7304:    $env{'form.scantron.first_bubble_line.n'} and
                   7305:    $env{"form.scantron.sub_bubblelines.n"}
1.447     foxr     7306:    which are the total number of bubble, lines, the number of bubble
1.503     raeburn  7307:    lines for response n and number of the first bubble line for response n,
                   7308:    and a comma separated list of numbers of bubble lines for sub-questions
1.509     raeburn  7309:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
1.424     albertel 7310: 
1.423     albertel 7311: =cut
                   7312: 
1.503     raeburn  7313: sub scantron_get_maxbubble {
1.257     albertel 7314:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7315: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7316: 	&restore_bubble_lines();
1.257     albertel 7317: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7318:     }
1.330     albertel 7319: 
1.447     foxr     7320:     my (undef, undef, $sequence) =
1.257     albertel 7321: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7322: 
1.447     foxr     7323:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 7324:     my $map=$navmap->getResourceByUrl($sequence);
                   7325:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7326: 
                   7327:     &Apache::lonxml::clear_problem_counter();
                   7328: 
1.435     foxr     7329:     my $uname       = $env{'form.student'};
                   7330:     my $udom        = $env{'form.userdom'};
                   7331:     my $cid         = $env{'request.course.id'};
                   7332:     my $total_lines = 0;
                   7333:     %bubble_lines_per_response = ();
1.447     foxr     7334:     %first_bubble_line         = ();
1.503     raeburn  7335:     %subdivided_bubble_lines   = ();
                   7336:     %responsetype_per_response = ();
1.447     foxr     7337:   
                   7338:     my $response_number = 0;
                   7339:     my $bubble_line     = 0;
1.191     albertel 7340:     foreach my $resource (@resources) {
1.528.2.4  raeburn  7341:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7342:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7343:             foreach my $part_id (@{$parts}) {
                   7344: 
                   7345:                 my $lines;
                   7346: 
                   7347: 	        # TODO - make this a persistent hash not an array.
                   7348: 
                   7349:                 # optionresponse, matchresponse and rankresponse type items 
                   7350:                 # render as separate sub-questions in exam mode.
                   7351:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7352:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7353:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7354:                     my ($numbub,$numshown);
                   7355:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7356:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
1.528.2.5  raeburn  7357:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
1.528.2.4  raeburn  7358:                         }
                   7359:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
1.528.2.5  raeburn  7360:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7361:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
1.528.2.4  raeburn  7362:                         }
                   7363:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7364:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7365:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7366:                         }
                   7367:                     }
                   7368:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7369:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7370:                     }
                   7371:                     my $bubbles_per_line = 10;
                   7372:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7373:                     if (($numbub % $bubbles_per_line) != 0) {
                   7374:                         $inner_bubble_lines++;
                   7375:                     }
                   7376:                     for (my $i=0; $i<$numshown; $i++) {
                   7377:                         $subdivided_bubble_lines{$response_number} .= 
                   7378:                             $inner_bubble_lines.',';
                   7379:                     }
                   7380:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7381:                     $lines = $numshown * $inner_bubble_lines;
                   7382:                 } else {
                   7383:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7384:                 } 
                   7385: 
                   7386:                 $first_bubble_line{$response_number} = $bubble_line;
                   7387: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7388:                 $responsetype_per_response{$response_number} = 
                   7389:                     $analysis->{$part_id.'.type'};
                   7390: 	        $response_number++;
                   7391: 
                   7392: 	        $bubble_line +=  $lines;
                   7393: 	        $total_lines +=  $lines;
                   7394: 	    }
                   7395:         }
                   7396:     }
1.528.2.11  raeburn  7397:     &Apache::lonnet::delenv('scantron.');
1.528.2.4  raeburn  7398: 
                   7399:     &save_bubble_lines();
                   7400:     $env{'form.scantron_maxbubble'} =
                   7401: 	$total_lines;
                   7402:     return $env{'form.scantron_maxbubble'};
                   7403: }
1.523     raeburn  7404: 
1.528.2.4  raeburn  7405: sub scantron_partids_tograde {
                   7406:     my ($resource,$cid,$uname,$udom) = @_;
                   7407:     my (%analysis,@parts);
1.435     foxr     7408: 
1.528.2.4  raeburn  7409:     if (ref($resource)) {
                   7410:         my $symb = $resource->symb();
1.523     raeburn  7411:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
                   7412:                                         ('symb' => $symb,
                   7413:                                          'grade_target' => 'analyze',
                   7414:                                          'grade_courseid' => $cid,
                   7415:                                          'grade_domain' => $udom,
                   7416:                                          'grade_username' => $uname));
1.528.2.4  raeburn  7417:         my (undef, $an) = split(/_HASH_REF__/,$result, 2);
                   7418:         %analysis = &Apache::lonnet::str2hash($an);
1.435     foxr     7419: 
1.503     raeburn  7420:         if (ref($analysis{'parts'}) eq 'ARRAY') {
1.515     raeburn  7421:             foreach my $part (@{$analysis{'parts'}}) {
                   7422:                 my ($id,$respid) = split(/\./,$part);
                   7423:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                   7424:                     push(@parts,$part);
                   7425:                 }
                   7426:             }
1.503     raeburn  7427:         }
1.191     albertel 7428:     }
1.528.2.4  raeburn  7429:     return (\%analysis,\@parts);
1.191     albertel 7430: }
                   7431: 
1.423     albertel 7432: =pod
                   7433: 
                   7434: =item scantron_validate_missingbubbles
                   7435: 
1.424     albertel 7436:    Validates all scanlines in the selected file to not have any
1.447     foxr     7437:     answers that don't have bubbles that have not been verified
                   7438:     to be bubble free.
1.424     albertel 7439: 
1.423     albertel 7440: =cut
                   7441: 
1.157     albertel 7442: sub scantron_validate_missingbubbles {
                   7443:     my ($r,$currentphase) = @_;
                   7444:     #get student info
                   7445:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7446:     my %idmap=&username_to_idmap($classlist);
                   7447: 
                   7448:     #get scantron line setup
1.257     albertel 7449:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7450:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7451:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7452:     if (!$max_bubble) { $max_bubble=2**31; }
                   7453:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7454: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7455: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7456: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7457: 						 $scan_data);
                   7458: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7459: 	my @to_correct;
1.470     foxr     7460: 	
                   7461: 	# Probably here's where the error is...
                   7462: 
1.157     albertel 7463: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7464:             my $lastbubble;
                   7465:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7466:                my $question = $1;
                   7467:                my $subquestion = $2;
                   7468:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7469:                my $first = $first_bubble_line{$question-1};
                   7470:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7471:                my $subcount = 1;
                   7472:                while ($subcount<$subquestion) {
                   7473:                    $first += $subans[$subcount-1];
                   7474:                    $subcount ++;
                   7475:                }
                   7476:                my $count = $subans[$subquestion-1];
                   7477:                $lastbubble = $first + $count;
                   7478:             } else {
                   7479:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7480:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7481:             }
                   7482:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7483: 	    push(@to_correct,$missing);
                   7484: 	}
                   7485: 	if (@to_correct) {
                   7486: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7487: 				     $line,'missingbubble',\@to_correct);
                   7488: 	    return (1,$currentphase);
                   7489: 	}
                   7490: 
                   7491:     }
                   7492:     return (0,$currentphase+1);
                   7493: }
                   7494: 
1.423     albertel 7495: =pod
                   7496: 
                   7497: =item scantron_process_students
                   7498: 
                   7499:    Routine that does the actual grading of the bubble sheet information.
                   7500: 
                   7501:    The parsed scanline hash is added to %env 
                   7502: 
                   7503:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   7504:    foreach resource , with the form data of
                   7505: 
                   7506: 	'submitted'     =>'scantron' 
                   7507: 	'grade_target'  =>'grade',
                   7508: 	'grade_username'=> username of student
                   7509: 	'grade_domain'  => domain of student
                   7510: 	'grade_courseid'=> of course
                   7511: 	'grade_symb'    => symb of resource to grade
                   7512: 
                   7513:     This triggers a grading pass. The problem grading code takes care
                   7514:     of converting the bubbled letter information (now in %env) into a
                   7515:     valid submission.
                   7516: 
                   7517: =cut
                   7518: 
1.82      albertel 7519: sub scantron_process_students {
1.75      albertel 7520:     my ($r) = @_;
1.513     foxr     7521: 
1.257     albertel 7522:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7523:     my ($symb)=&get_symb($r);
1.513     foxr     7524:     if (!$symb) {
                   7525: 	return '';
                   7526:     }
1.324     albertel 7527:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7528: 
1.257     albertel 7529:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7530:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7531:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7532:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7533:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7534:     my $map=$navmap->getResourceByUrl($sequence);
                   7535:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.528.2.4  raeburn  7536: 
                   7537:     my ($uname,$udom,%partids_by_symb);
                   7538:     foreach my $resource (@resources) {
                   7539:         my $ressymb = $resource->symb();
                   7540:         my ($analysis,$parts) =
                   7541:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7542:         $partids_by_symb{$ressymb} = $parts;
                   7543:     }
1.140     albertel 7544: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 7545:     my $result= <<SCANTRONFORM;
1.81      albertel 7546: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7547:   <input type="hidden" name="command" value="scantron_configphase" />
                   7548:   $default_form_data
                   7549: SCANTRONFORM
1.82      albertel 7550:     $r->print($result);
                   7551: 
                   7552:     my @delayqueue;
1.528.2.4  raeburn  7553:     my (%completedstudents,,%scandata);
1.140     albertel 7554:     
1.520     www      7555:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7556:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7557:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7558:  				    'Scantron Progress',$count,
1.195     albertel 7559: 				    'inline',undef,'scantronupload');
1.140     albertel 7560:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7561: 					  'Processing first student');
1.528.2.4  raeburn  7562:     $r->print('<br />');
1.140     albertel 7563:     my $start=&Time::HiRes::time();
1.158     albertel 7564:     my $i=-1;
1.528.2.4  raeburn  7565:     my $started;
1.447     foxr     7566: 
                   7567:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
1.513     foxr     7568:     
                   7569: 
                   7570:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7571:     # the user and return.
                   7572: 
                   7573:     if ($ssi_error) {
                   7574: 	$r->print("</form>");
                   7575: 	&ssi_print_error($r);
                   7576: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7577:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7578: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7579:     }
1.447     foxr     7580: 
1.528.2.4  raeburn  7581:     my %lettdig = &letter_to_digits();
                   7582:     my $numletts = scalar(keys(%lettdig));
                   7583: 
1.157     albertel 7584:     while ($i<$scanlines->{'count'}) {
                   7585:  	($uname,$udom)=('','');
                   7586:  	$i++;
1.200     albertel 7587:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7588:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7589: 	if ($started) {
                   7590: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7591: 						     'last student');
                   7592: 	}
                   7593: 	$started=1;
1.157     albertel 7594:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7595:  						 $scan_data);
                   7596:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7597:  					      \%idmap,$i)) {
                   7598:   	    &scantron_add_delay(\@delayqueue,$line,
                   7599:  				'Unable to find a student that matches',1);
                   7600:  	    next;
                   7601:   	}
                   7602:  	if (exists $completedstudents{$uname}) {
                   7603:  	    &scantron_add_delay(\@delayqueue,$line,
                   7604:  				'Student '.$uname.' has multiple sheets',2);
                   7605:  	    next;
                   7606:  	}
                   7607:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7608: 
                   7609: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7610:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7611: 
                   7612: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7613: 	    &scantron_putfile($scanlines,$scan_data);
                   7614: 	}
1.513     foxr     7615: 
1.528.2.4  raeburn  7616:         my $scancode;
                   7617:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7618:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7619:             $scancode = $scan_record->{'scantron.CODE'};
                   7620:         } else {
                   7621:             $scancode = '';
                   7622:         }
                   7623: 
                   7624:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7625:                                    @resources) eq 'ssi_error') {
                   7626:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7627:             $r->print("</form>");
                   7628:             &ssi_print_error($r);
                   7629:             $r->print(&show_grading_menu_form($symb));
                   7630:             &Apache::lonnet::remove_lock($lock);
                   7631:             return '';      # Why return ''?  Beats me.
                   7632:         }
                   7633: 
1.140     albertel 7634: 	$completedstudents{$uname}={'line'=>$line};
1.528.2.4  raeburn  7635:         if ($env{'form.verifyrecord'}) {
                   7636:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7637:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7638:             chomp($studentdata);
                   7639:             $studentdata =~ s/\r$//;
                   7640:             my $studentrecord = '';
                   7641:             my $counter = -1;
                   7642:             foreach my $resource (@resources) {
                   7643:                 ($counter,my $recording) =
                   7644:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
                   7645:                                              $counter,$studentdata,\%partids_by_symb,
                   7646:                                              \%scantron_config,\%lettdig,$numletts);
                   7647:                 $studentrecord .= $recording;
                   7648:             }
                   7649:             if ($studentrecord ne $studentdata) {
1.528.2.11  raeburn  7650:                 &Apache::lonxml::clear_problem_counter();
                   7651:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7652:                                            \@resources) eq 'ssi_error') {
                   7653:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7654:                     $r->print("</form>");
                   7655:                     &ssi_print_error($r);
                   7656:                     $r->print(&show_grading_menu_form($symb));
                   7657:                     &Apache::lonnet::remove_lock($lock);
                   7658:                     delete($completedstudents{$uname});
                   7659:                     return '';
                   7660:                 }
1.528.2.4  raeburn  7661:                 $counter = -1;
                   7662:                 $studentrecord = '';
                   7663:                 foreach my $resource (@resources) {
                   7664:                     ($counter,my $recording) =
                   7665:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
                   7666:                                                  $counter,$studentdata,\%partids_by_symb,
                   7667:                                                  \%scantron_config,\%lettdig,$numletts);
                   7668:                     $studentrecord .= $recording;
                   7669:                 }
                   7670:                 if ($studentrecord ne $studentdata) {
                   7671:                     $r->print('<p><span class="LC_error">');
                   7672:                     if ($scancode eq '') {
                   7673:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7674:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7675:                     } else {
                   7676:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7677:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7678:                     }
                   7679:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7680:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7681:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7682:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7683:                               &Apache::loncommon::start_data_table_row().
                   7684:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7685:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7686:                               &Apache::loncommon::end_data_table_row().
                   7687:                               &Apache::loncommon::start_data_table_row().
                   7688:                               '<td>Stored submissions</td>'.
                   7689:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7690:                               &Apache::loncommon::end_data_table_row().
                   7691:                               &Apache::loncommon::end_data_table().'</p>');
                   7692:                 } else {
                   7693:                     $r->print('<br /><span class="LC_warning">'.
                   7694:                              &mt('A second grading pass was needed for user: [_1] with ID: [_2], because a mismatch was seen on the first pass.',$uname.':'.$udom,$scan_record->{'scantron.ID'}).'<br />'.
                   7695:                              &mt("As a consequence, this user's submission history records two tries.").
                   7696:                                  '</span><br />');
                   7697:                 }
                   7698:             }
                   7699:         }
1.213     albertel 7700: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7701:     } continue {
1.330     albertel 7702: 	&Apache::lonxml::clear_problem_counter();
1.528.2.11  raeburn  7703: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7704:     }
1.140     albertel 7705:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7706:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7707: #    my $lasttime = &Time::HiRes::time()-$start;
                   7708: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7709: 
1.200     albertel 7710:     $r->print("</form>");
1.324     albertel 7711:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7712:     return '';
1.75      albertel 7713: }
1.157     albertel 7714: 
1.528.2.4  raeburn  7715: sub grade_student_bubbles {
                   7716:     my ($r,$uname,$udom,$scan_record,$scancode,@resources) = @_;
                   7717:     foreach my $resource (@resources) {
                   7718:         my %form = ('submitted'     => 'scantron',
                   7719:                     'grade_target'  => 'grade',
                   7720:                     'grade_username'=> $uname,
                   7721:                     'grade_domain'  => $udom,
                   7722:                     'grade_courseid'=> $env{'request.course.id'},
                   7723:                     'grade_symb'    => $resource->symb(),
1.528.2.10  raeburn  7724:                     'CODE'          => $scancode);
1.528.2.4  raeburn  7725:         my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7726:         return 'ssi_error' if ($ssi_error);
                   7727:         last if (&Apache::loncommon::connection_aborted($r));
                   7728:     }
                   7729:     return;
                   7730: }
                   7731: 
1.423     albertel 7732: =pod
                   7733: 
                   7734: =item scantron_upload_scantron_data
                   7735: 
                   7736:     Creates the screen for adding a new bubble sheet data file to a course.
                   7737: 
                   7738: =cut
                   7739: 
1.157     albertel 7740: sub scantron_upload_scantron_data {
                   7741:     my ($r)=@_;
1.257     albertel 7742:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7743:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7744: 							  'domainid',
                   7745: 							  'coursename');
1.257     albertel 7746:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7747: 						   'domainid');
1.324     albertel 7748:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7749:     $r->print('
1.157     albertel 7750: <script type="text/javascript" language="javascript">
                   7751:     function checkUpload(formname) {
                   7752: 	if (formname.upfile.value == "") {
1.528.2.12! raeburn  7753: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.157     albertel 7754: 	    return false;
                   7755: 	}
                   7756: 	formname.submit();
                   7757:     }
                   7758: </script>
                   7759: 
1.492     albertel 7760: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7761: '.$default_form_data.'
1.181     albertel 7762: <table>
1.492     albertel 7763: <tr><td>'.$select_link.'                             </td></tr>
                   7764: <tr><td>'.&mt('Course ID:').'     </td>
                   7765:     <td><input name="courseid"   type="text" />      </td></tr>
                   7766: <tr><td>'.&mt('Course Name:').'   </td>
                   7767:     <td><input name="coursename" type="text" />      </td></tr>
                   7768: <tr><td>'.&mt('Domain:').'        </td>
                   7769:     <td>'.$domsel.'                                  </td></tr>
                   7770: <tr><td>'.&mt('File to upload:').'</td>
                   7771:     <td><input type="file" name="upfile" size="50" /></td></tr>
1.181     albertel 7772: </table>
1.492     albertel 7773: <input name="command" value="scantronupload_save" type="hidden" />
                   7774: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.157     albertel 7775: </form>
1.492     albertel 7776: ');
1.157     albertel 7777:     return '';
                   7778: }
                   7779: 
1.423     albertel 7780: =pod
                   7781: 
                   7782: =item scantron_upload_scantron_data_save
                   7783: 
                   7784:    Adds a provided bubble information data file to the course if user
                   7785:    has the correct privileges to do so.  
                   7786: 
                   7787: =cut
                   7788: 
1.157     albertel 7789: sub scantron_upload_scantron_data_save {
                   7790:     my($r)=@_;
1.324     albertel 7791:     my ($symb)=&get_symb($r,1);
1.182     albertel 7792:     my $doanotherupload=
                   7793: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7794: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7795: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7796: 	'</form>'."\n";
1.257     albertel 7797:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7798: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7799: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.492     albertel 7800: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
1.182     albertel 7801: 	if ($symb) {
1.324     albertel 7802: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7803: 	} else {
                   7804: 	    $r->print($doanotherupload);
                   7805: 	}
1.162     albertel 7806: 	return '';
                   7807:     }
1.257     albertel 7808:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.492     albertel 7809:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
1.257     albertel 7810:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7811:     #FIXME
                   7812:     #copied from lonnet::userfileupload()
                   7813:     #make that function able to target a specified course
                   7814:     # Replace Windows backslashes by forward slashes
                   7815:     $fname=~s/\\/\//g;
                   7816:     # Get rid of everything but the actual filename
                   7817:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7818:     # Replace spaces by underscores
                   7819:     $fname=~s/\s+/\_/g;
                   7820:     # Replace all other weird characters by nothing
                   7821:     $fname=~s/[^\w\.\-]//g;
                   7822:     # See if there is anything left
                   7823:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7824:     my $uploadedfile=$fname;
1.157     albertel 7825:     $fname='scantron_orig_'.$fname;
1.257     albertel 7826:     if (length($env{'form.upfile'}) < 2) {
1.492     albertel 7827: 	$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 7828:     } else {
1.275     albertel 7829: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7830: 	if ($result =~ m|^/uploaded/|) {
1.492     albertel 7831: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
                   7832: 			  (length($env{'form.upfile'})-1),
                   7833: 			  '<span class="LC_filename">'.$result."</span>"));
1.210     albertel 7834: 	} else {
1.492     albertel 7835: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
                   7836: 			  $result,
                   7837: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
                   7838: 
1.183     albertel 7839: 	}
                   7840:     }
1.174     albertel 7841:     if ($symb) {
1.209     ng       7842: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7843:     } else {
1.182     albertel 7844: 	$r->print($doanotherupload);
1.174     albertel 7845:     }
1.157     albertel 7846:     return '';
                   7847: }
                   7848: 
1.423     albertel 7849: =pod
                   7850: 
                   7851: =item valid_file
                   7852: 
1.424     albertel 7853:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7854: 
                   7855: =cut
                   7856: 
1.202     albertel 7857: sub valid_file {
                   7858:     my ($requested_file)=@_;
                   7859:     foreach my $filename (sort(&scantron_filenames())) {
                   7860: 	if ($requested_file eq $filename) { return 1; }
                   7861:     }
                   7862:     return 0;
                   7863: }
                   7864: 
1.423     albertel 7865: =pod
                   7866: 
                   7867: =item scantron_download_scantron_data
                   7868: 
                   7869:    Shows a list of the three internal files (original, corrected,
                   7870:    skipped) for a specific bubble sheet data file that exists in the
                   7871:    course.
                   7872: 
                   7873: =cut
                   7874: 
1.202     albertel 7875: sub scantron_download_scantron_data {
                   7876:     my ($r)=@_;
1.324     albertel 7877:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7878:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7879:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7880:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7881:     if (! &valid_file($file)) {
1.492     albertel 7882: 	$r->print('
1.202     albertel 7883: 	<p>
1.492     albertel 7884: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7885:         </p>
1.492     albertel 7886: ');
1.324     albertel 7887: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7888: 	return;
                   7889:     }
                   7890:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7891:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7892:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7893:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7894:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7895:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7896:     $r->print('
1.202     albertel 7897:     <p>
1.492     albertel 7898: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7899: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7900:     </p>
                   7901:     <p>
1.492     albertel 7902: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7903: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7904:     </p>
                   7905:     <p>
1.492     albertel 7906: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7907: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7908:     </p>
1.492     albertel 7909: ');
1.324     albertel 7910:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7911:     return '';
                   7912: }
1.157     albertel 7913: 
1.523     raeburn  7914: sub checkscantron_results {
                   7915:     my ($r) = @_;
                   7916:     my ($symb)=&get_symb($r);
                   7917:     if (!$symb) {return '';}
                   7918:     my $grading_menu_button=&show_grading_menu_form($symb);
                   7919:     my $cid = $env{'request.course.id'};
1.528.2.4  raeburn  7920:     my %lettdig = &letter_to_digits();
1.523     raeburn  7921:     my $numletts = scalar(keys(%lettdig));
                   7922:     my $cnum = $env{'course.'.$cid.'.num'};
                   7923:     my $cdom = $env{'course.'.$cid.'.domain'};
                   7924:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7925:     my %record;
                   7926:     my %scantron_config =
                   7927:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   7928:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   7929:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7930:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   7931:     my $navmap=Apache::lonnavmaps::navmap->new();
                   7932:     my $map=$navmap->getResourceByUrl($sequence);
                   7933:     my @resources=$navmap->retrieveResources($map,undef,1,0);
1.528.2.4  raeburn  7934:     my ($uname,$udom,%partids_by_symb);
                   7935:     foreach my $resource (@resources) {
                   7936:         my $ressymb = $resource->symb();
                   7937:         my ($analysis,$parts) =
                   7938:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7939:         $partids_by_symb{$ressymb} = $parts;
                   7940:     }
1.523     raeburn  7941:     my (%scandata,%lastname,%bylast);
                   7942:     $r->print('
                   7943: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   7944: 
                   7945:     my @delayqueue;
                   7946:     my %completedstudents;
                   7947: 
                   7948:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
                   7949:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
                   7950:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
                   7951:                                     'inline',undef,'checkscantron');
1.528.2.8  raeburn  7952:     my ($username,$domain,$started);
1.523     raeburn  7953: 
                   7954:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
                   7955: 
                   7956:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7957:                                           'Processing first student');
                   7958:     my $start=&Time::HiRes::time();
                   7959:     my $i=-1;
                   7960: 
                   7961:     while ($i<$scanlines->{'count'}) {
                   7962:         ($username,$domain,$uname)=('','','');
                   7963:         $i++;
                   7964:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   7965:         if ($line=~/^[\s\cz]*$/) { next; }
                   7966:         if ($started) {
                   7967:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7968:                                                      'last student');
                   7969:         }
                   7970:         $started=1;
                   7971:         my $scan_record=
                   7972:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   7973:                                                      $scan_data);
                   7974:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   7975:                                                               \%idmap,$i)) {
                   7976:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7977:                                 'Unable to find a student that matches',1);
                   7978:             next;
                   7979:         }
                   7980:         if (exists $completedstudents{$uname}) {
                   7981:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7982:                                 'Student '.$uname.' has multiple sheets',2);
                   7983:             next;
                   7984:         }
                   7985:         my $pid = $scan_record->{'scantron.ID'};
                   7986:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   7987:         push(@{$bylast{$lastname{$pid}}},$pid);
                   7988:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7989:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7990:         chomp($scandata{$pid});
                   7991:         $scandata{$pid} =~ s/\r$//;
                   7992:         ($username,$domain)=split(/:/,$uname);
                   7993:         my $counter = -1;
                   7994:         foreach my $resource (@resources) {
1.528.2.4  raeburn  7995:             ($counter,my $recording) =
                   7996:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
                   7997:                                          $scandata{$pid},\%partids_by_symb,
                   7998:                                          \%scantron_config,\%lettdig,$numletts);
                   7999:             $record{$pid} .= $recording;
1.523     raeburn  8000:         }
                   8001:     }
                   8002:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8003:     $r->print('<br />');
                   8004:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8005:     $passed = 0;
                   8006:     $failed = 0;
                   8007:     $numstudents = 0;
                   8008:     foreach my $last (sort(keys(%bylast))) {
                   8009:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8010:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8011:                 my $showscandata = $scandata{$pid};
                   8012:                 my $showrecord = $record{$pid};
                   8013:                 $showscandata =~ s/\s/&nbsp;/g;
                   8014:                 $showrecord =~ s/\s/&nbsp;/g;
                   8015:                 if ($scandata{$pid} eq $record{$pid}) {
                   8016:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8017:                     $okstudents .= '<tr class="'.$css_class.'">'.
                   8018: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8019: '</tr>'."\n".
                   8020: '<tr class="'.$css_class.'">'."\n".
                   8021: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8022:                     $passed ++;
                   8023:                 } else {
                   8024:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
                   8025:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8026: '</tr>'."\n".
                   8027: '<tr class="'.$css_class.'">'."\n".
                   8028: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8029: '</tr>'."\n";
                   8030:                     $failed ++;
                   8031:                 }
                   8032:                 $numstudents ++;
                   8033:             }
                   8034:         }
                   8035:     }
                   8036:     $r->print('<p>'.&mt('Comparison of scantron data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
                   8037:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
                   8038:     if ($passed) {
                   8039:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
                   8040:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8041:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8042:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8043:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8044:                  $okstudents."\n".
                   8045:                  &Apache::loncommon::end_data_table().'<br />');
                   8046:     }
                   8047:     if ($failed) {
                   8048:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
                   8049:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8050:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8051:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8052:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8053:                  $badstudents."\n".
                   8054:                  &Apache::loncommon::end_data_table()).'<br />'.
                   8055:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
                   8056:     }
                   8057:     $r->print('</form><br />'.$grading_menu_button);
                   8058:     return;
                   8059: }
                   8060: 
1.528.2.4  raeburn  8061: sub verify_scantron_grading {
                   8062:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids_by_symb,
                   8063:         $scantron_config,$lettdig,$numletts) = @_;
                   8064:     my ($record,%expected,%startpos);
                   8065:     return ($counter,$record) if (!ref($resource));
                   8066:     return ($counter,$record) if (!$resource->is_problem());
                   8067:     my $symb = $resource->symb();
                   8068:     return ($counter,$record) if (ref($partids_by_symb) ne 'HASH');
                   8069:     return ($counter,$record) if (ref($partids_by_symb->{$symb}) ne 'ARRAY');
                   8070:     foreach my $part_id (@{$partids_by_symb->{$symb}}) {
                   8071:         $counter ++;
                   8072:         $expected{$part_id} = 0;
                   8073:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8074:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8075:             foreach my $item (@sub_lines) {
                   8076:                 $expected{$part_id} += $item;
                   8077:             }
                   8078:         } else {
                   8079:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8080:         }
                   8081:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8082:     }
                   8083:     if ($symb) {
                   8084:         my %recorded;
                   8085:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8086:         if ($returnhash{'version'}) {
                   8087:             my %lasthash=();
                   8088:             my $version;
                   8089:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8090:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8091:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8092:                 }
                   8093:             }
                   8094:             foreach my $key (keys(%lasthash)) {
                   8095:                 if ($key =~ /\.scantron$/) {
                   8096:                     my $value = &unescape($lasthash{$key});
                   8097:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8098:                     if ($value eq '') {
                   8099:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8100:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8101:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8102:                             }
                   8103:                         }
                   8104:                     } else {
                   8105:                         my @tocheck;
                   8106:                         my @items = split(//,$value);
                   8107:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8108:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8109:                             if (@items < $expected{$part_id}) {
                   8110:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8111:                                 my @singles = split(//,$fragment);
                   8112:                                 foreach my $pos (@singles) {
                   8113:                                     if ($pos eq ' ') {
                   8114:                                         push(@tocheck,$pos);
                   8115:                                     } else {
                   8116:                                         my $next = shift(@items);
                   8117:                                         push(@tocheck,$next);
                   8118:                                     }
                   8119:                                 }
                   8120:                             } else {
                   8121:                                 @tocheck = @items;
                   8122:                             }
                   8123:                             foreach my $letter (@tocheck) {
                   8124:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8125:                                     if ($letter !~ /^[A-J]$/) {
                   8126:                                         $letter = $scantron_config->{'Qoff'};
                   8127:                                     }
                   8128:                                     $recorded{$part_id} .= $letter;
                   8129:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8130:                                     my $digit;
                   8131:                                     if ($letter !~ /^[A-J]$/) {
                   8132:                                         $digit = $scantron_config->{'Qoff'};
                   8133:                                     } else {
                   8134:                                         $digit = $lettdig->{$letter};
                   8135:                                     }
                   8136:                                     $recorded{$part_id} .= $digit;
                   8137:                                 }
                   8138:                             }
                   8139:                         } else {
                   8140:                             @tocheck = @items;
                   8141:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8142:                                 my $curr_sub = shift(@tocheck);
                   8143:                                 my $digit;
                   8144:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8145:                                     $digit = $lettdig->{$curr_sub}-1;
                   8146:                                 }
                   8147:                                 if ($curr_sub eq 'J') {
                   8148:                                     $digit += scalar($numletts);
                   8149:                                 }
                   8150:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8151:                                     if ($j == $digit) {
                   8152:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8153:                                     } else {
                   8154:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8155:                                     }
                   8156:                                 }
                   8157:                             }
                   8158:                         }
                   8159:                     }
                   8160:                 }
                   8161:             }
                   8162:         }
                   8163:         foreach my $part_id (@{$partids_by_symb->{$symb}}) {
                   8164:             if ($recorded{$part_id} eq '') {
                   8165:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8166:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8167:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8168:                     }
                   8169:                 }
                   8170:             }
                   8171:             $record .= $recorded{$part_id};
                   8172:         }
                   8173:     }
                   8174:     return ($counter,$record);
                   8175: }
                   8176: 
                   8177: sub letter_to_digits {
                   8178:     my %lettdig = (
                   8179:                     A => 1,
                   8180:                     B => 2,
                   8181:                     C => 3,
                   8182:                     D => 4,
                   8183:                     E => 5,
                   8184:                     F => 6,
                   8185:                     G => 7,
                   8186:                     H => 8,
                   8187:                     I => 9,
                   8188:                     J => 0,
                   8189:                   );
                   8190:     return %lettdig;
                   8191: }
                   8192: 
1.423     albertel 8193: =pod
                   8194: 
                   8195: =back
                   8196: 
                   8197: =cut
                   8198: 
1.75      albertel 8199: #-------- end of section for handling grading scantron forms -------
                   8200: #
                   8201: #-------------------------------------------------------------------
                   8202: 
1.72      ng       8203: #-------------------------- Menu interface -------------------------
                   8204: #
                   8205: #--- Show a Grading Menu button - Calls the next routine ---
                   8206: sub show_grading_menu_form {
1.324     albertel 8207:     my ($symb)=@_;
1.125     ng       8208:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8209: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8210: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8211: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8212: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8213: 	'</form>'."\n";
                   8214:     return $result;
                   8215: }
                   8216: 
1.77      ng       8217: # -- Retrieve choices for grading form
                   8218: sub savedState {
                   8219:     my %savedState = ();
1.257     albertel 8220:     if ($env{'form.saveState'}) {
                   8221: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8222: 	    my ($key,$value) = split(/=/,$_,2);
                   8223: 	    $savedState{$key} = $value;
                   8224: 	}
                   8225:     }
                   8226:     return \%savedState;
                   8227: }
1.76      ng       8228: 
1.443     banghart 8229: sub grading_menu {
                   8230:     my ($request) = @_;
                   8231:     my ($symb)=&get_symb($request);
                   8232:     if (!$symb) {return '';}
                   8233:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8234:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8235: 
1.444     banghart 8236:     $request->print($table);
1.443     banghart 8237:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8238:                   'handgrade'=>$hdgrade,
                   8239:                   'probTitle'=>$probTitle,
                   8240:                   'command'=>'submit_options',
                   8241:                   'saveState'=>"",
                   8242:                   'gradingMenu'=>1,
                   8243:                   'showgrading'=>"yes");
                   8244:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8245:     my @menu = ({ url => $url,
                   8246:                      name => &mt('Manual Grading/View Submissions'),
                   8247:                      short_description => 
                   8248:     &mt('Start the process of hand grading submissions.'),
                   8249:                  });
                   8250:     $fields{'command'} = 'csvform';
                   8251:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8252:     push(@menu, { url => $url,
1.443     banghart 8253:                    name => &mt('Upload Scores'),
                   8254:                    short_description => 
                   8255:             &mt('Specify a file containing the class scores for current resource.')});
                   8256:     $fields{'command'} = 'processclicker';
                   8257:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8258:     push(@menu, { url => $url,
1.443     banghart 8259:                    name => &mt('Process Clicker'),
                   8260:                    short_description => 
                   8261:             &mt('Specify a file containing the clicker information for this resource.')});
                   8262:     $fields{'command'} = 'scantron_selectphase';
                   8263:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8264:     push(@menu, { url => $url,
1.523     raeburn  8265:                    name => &mt('Grade/Manage/Review Scantron Forms'),
1.454     banghart 8266:                    short_description => 
1.523     raeburn  8267:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
1.443     banghart 8268:     $fields{'command'} = 'verify';
                   8269:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8270:     push(@menu, { url => "",
1.443     banghart 8271:                    name => &mt('Verify Receipt'),
                   8272:                    short_description => 
                   8273:             &mt('')});
                   8274:     #
                   8275:     # Create the menu
                   8276:     my $Str;
1.444     banghart 8277:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8278:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8279:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8280:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8281: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8282: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8283: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8284: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8285: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8286: 
1.443     banghart 8287:     foreach my $menudata (@menu) {
1.445     banghart 8288:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   8289:             $Str .='    <h3><a '.
                   8290:                 $menudata->{'jscript'}.
                   8291:                 ' href="'.
                   8292:                 $menudata->{'url'}.'" >'.
                   8293:                 $menudata->{'name'}."</a></h3>\n";
                   8294:         } else {
1.511     www      8295:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
1.445     banghart 8296:                 $menudata->{'jscript'}.
1.458     banghart 8297:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.511     www      8298:                 ' /> '.
                   8299: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
                   8300:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 8301:         }
1.443     banghart 8302:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   8303:             "\n";
                   8304:     }
1.444     banghart 8305:     $Str .="</form>\n";
1.528.2.11  raeburn  8306:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 8307:     $request->print(<<GRADINGMENUJS);
                   8308: <script type="text/javascript" language="javascript">
                   8309:     function checkChoice(formname,val,cmdx) {
                   8310: 	if (val <= 2) {
                   8311: 	    var cmd = radioSelection(formname.radioChoice);
                   8312: 	    var cmdsave = cmd;
                   8313: 	} else {
                   8314: 	    cmd = cmdx;
                   8315: 	    cmdsave = 'submission';
                   8316: 	}
                   8317: 	formname.command.value = cmd;
                   8318: 	if (val < 5) formname.submit();
                   8319: 	if (val == 5) {
1.458     banghart 8320: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8321: 	        return false;
                   8322: 	    } else {
                   8323: 	        formname.submit();
                   8324: 	    }
1.445     banghart 8325: 	}
                   8326:     }
1.443     banghart 8327: 
                   8328:     function checkReceiptNo(formname,nospace) {
                   8329: 	var receiptNo = formname.receipt.value;
                   8330: 	var checkOpt = false;
                   8331: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8332: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8333: 	if (checkOpt) {
1.528.2.11  raeburn  8334: 	    alert("$receiptalert$receiptalert");
1.443     banghart 8335: 	    formname.receipt.value = "";
                   8336: 	    formname.receipt.focus();
                   8337: 	    return false;
                   8338: 	}
                   8339: 	return true;
                   8340:     }
                   8341: </script>
                   8342: GRADINGMENUJS
                   8343:     &commonJSfunctions($request);
                   8344:     return $Str;    
                   8345: }
                   8346: 
                   8347: 
                   8348: #--- Displays the submissions first page -------
                   8349: sub submit_options {
1.72      ng       8350:     my ($request) = @_;
1.324     albertel 8351:     my ($symb)=&get_symb($request);
1.72      ng       8352:     if (!$symb) {return '';}
1.76      ng       8353:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8354: 
1.528.2.11  raeburn  8355:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       8356:     $request->print(<<GRADINGMENUJS);
                   8357: <script type="text/javascript" language="javascript">
1.116     ng       8358:     function checkChoice(formname,val,cmdx) {
                   8359: 	if (val <= 2) {
                   8360: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8361: 	    var cmdsave = cmd;
1.116     ng       8362: 	} else {
                   8363: 	    cmd = cmdx;
1.118     ng       8364: 	    cmdsave = 'submission';
1.116     ng       8365: 	}
                   8366: 	formname.command.value = cmd;
1.118     ng       8367: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8368: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8369: 	if (val < 5) formname.submit();
                   8370: 	if (val == 5) {
1.72      ng       8371: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8372: 	    formname.submit();
                   8373: 	}
1.238     albertel 8374: 	if (val < 7) formname.submit();
1.72      ng       8375:     }
                   8376: 
                   8377:     function checkReceiptNo(formname,nospace) {
                   8378: 	var receiptNo = formname.receipt.value;
                   8379: 	var checkOpt = false;
                   8380: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8381: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8382: 	if (checkOpt) {
1.528.2.11  raeburn  8383: 	    alert("$receiptalert");
1.72      ng       8384: 	    formname.receipt.value = "";
                   8385: 	    formname.receipt.focus();
                   8386: 	    return false;
                   8387: 	}
                   8388: 	return true;
                   8389:     }
                   8390: </script>
                   8391: GRADINGMENUJS
1.118     ng       8392:     &commonJSfunctions($request);
1.324     albertel 8393:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8394:     my $result;
1.76      ng       8395:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8396:     my $savedState = &savedState();
1.118     ng       8397:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8398:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8399:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8400:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8401: 
                   8402:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8403: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8404: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8405: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8406: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8407: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8408: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8409: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8410: 
1.472     albertel 8411:     $result.='
                   8412:     <div class="LC_grade_select_mode">
1.473     albertel 8413:       <div class="LC_grade_select_mode_current">
                   8414:         <h2>
                   8415:           '.&mt('Grade Current Resource').'
                   8416:         </h2>
                   8417:         <div class="LC_grade_select_mode_body">
                   8418:           <div class="LC_grades_resource_info">
                   8419:            '.$table.'
                   8420:           </div>
                   8421:           <div class="LC_grade_select_mode_selector">
                   8422:              <div class="LC_grade_select_mode_selector_header">
                   8423:                 '.&mt('Sections').'
                   8424:              </div>
                   8425:              <div class="LC_grade_select_mode_selector_body">
                   8426: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       8427:     if (ref($sections)) {
1.524     raeburn  8428: 	foreach my $section (sort(@$sections)) {
1.472     albertel 8429: 	    $result.='<option value="'.$section.'" '.
                   8430: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 8431: 	}
1.116     ng       8432:     }
1.401     albertel 8433:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8434:     $result.='
1.473     albertel 8435:              </div>
                   8436:           </div>
                   8437:           <div class="LC_grade_select_mode_selector">
                   8438:              <div class="LC_grade_select_mode_selector_header">
                   8439:                 '.&mt('Groups').'
                   8440:              </div>
                   8441:              <div class="LC_grade_select_mode_selector_body">
                   8442:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8443:              </div>
1.472     albertel 8444:           </div>
1.473     albertel 8445:           <div class="LC_grade_select_mode_selector">
                   8446:              <div class="LC_grade_select_mode_selector_header">
                   8447:                 '.&mt('Access Status').'
                   8448:              </div>
                   8449:              <div class="LC_grade_select_mode_selector_body">
                   8450:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8451:              </div>
1.472     albertel 8452:           </div>
1.473     albertel 8453:           <div class="LC_grade_select_mode_selector">
                   8454:              <div class="LC_grade_select_mode_selector_header">
                   8455:                 '.&mt('Submission Status').'
                   8456:              </div>
                   8457:              <div class="LC_grade_select_mode_selector_body">
                   8458:                <select name="submitonly" size="5">
                   8459: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8460: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8461: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8462: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8463:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   8464:                </select>
                   8465:              </div>
1.472     albertel 8466:           </div>
1.473     albertel 8467:           <div class="LC_grade_select_mode_type_body">
                   8468:             <div class="LC_grade_select_mode_type">
                   8469:               <label>
                   8470:                 <input type="radio" name="radioChoice" value="submission" '.
                   8471:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8472:              &mt('Select individual students to grade and view submissions.').'
                   8473: 	      </label> 
                   8474:             </div>
                   8475:             <div class="LC_grade_select_mode_type">
                   8476: 	      <label>
                   8477:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8478:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8479:                     &mt('Grade all selected students in a grading table.').'
                   8480:               </label>
                   8481:             </div>
                   8482:             <div class="LC_grade_select_mode_type">
1.528.2.11  raeburn  8483: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8484:             </div>
1.472     albertel 8485:           </div>
1.473     albertel 8486:         </div>
                   8487:       </div>
                   8488:       <div class="LC_grade_select_mode_page">
                   8489:         <h2>
                   8490:          '.&mt('Grade Complete Folder for One Student').'
                   8491:         </h2>
                   8492:         <div class="LC_grades_select_mode_body">
                   8493:           <div class="LC_grade_select_mode_type_body">
                   8494:             <div class="LC_grade_select_mode_type">
                   8495:               <label>
                   8496:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8497: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8498:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8499:               </label>
                   8500:             </div>
                   8501:             <div class="LC_grade_select_mode_type">
1.528.2.11  raeburn  8502: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8503:             </div>
1.472     albertel 8504:           </div>
                   8505:         </div>
                   8506:       </div>
                   8507:     </div>
                   8508:   </form>';
1.499     albertel 8509:     $result .= &show_grading_menu_form($symb);
1.44      ng       8510:     return $result;
1.2       albertel 8511: }
                   8512: 
1.285     albertel 8513: sub reset_perm {
                   8514:     undef(%perm);
                   8515: }
                   8516: 
                   8517: sub init_perm {
                   8518:     &reset_perm();
1.300     albertel 8519:     foreach my $test_perm ('vgr','mgr','opa') {
                   8520: 
                   8521: 	my $scope = $env{'request.course.id'};
                   8522: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8523: 
                   8524: 	    $scope .= '/'.$env{'request.course.sec'};
                   8525: 	    if ( $perm{$test_perm}=
                   8526: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8527: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8528: 	    } else {
                   8529: 		delete($perm{$test_perm});
                   8530: 	    }
1.285     albertel 8531: 	}
                   8532:     }
                   8533: }
                   8534: 
1.400     www      8535: sub gather_clicker_ids {
1.408     albertel 8536:     my %clicker_ids;
1.400     www      8537: 
                   8538:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8539: 
                   8540:     # Set up a couple variables.
1.407     albertel 8541:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8542:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8543:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8544: 
1.407     albertel 8545:     foreach my $student (keys(%$classlist)) {
1.438     www      8546:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8547:         my $username = $classlist->{$student}->[$username_idx];
                   8548:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8549:         my $clickers =
1.408     albertel 8550: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8551:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8552:             $id=~s/^[\#0]+//;
1.421     www      8553:             $id=~s/[\-\:]//g;
1.407     albertel 8554:             if (exists($clicker_ids{$id})) {
1.408     albertel 8555: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8556:             } else {
1.408     albertel 8557: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8558:             }
                   8559:         }
                   8560:     }
1.407     albertel 8561:     return %clicker_ids;
1.400     www      8562: }
                   8563: 
1.402     www      8564: sub gather_adv_clicker_ids {
1.408     albertel 8565:     my %clicker_ids;
1.402     www      8566:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8567:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8568:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8569:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8570:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8571:             my ($puname,$pudom)=split(/\:/,$person);
                   8572:             my $clickers =
1.408     albertel 8573: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8574:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8575: 		$id=~s/^[\#0]+//;
1.421     www      8576:                 $id=~s/[\-\:]//g;
1.408     albertel 8577: 		if (exists($clicker_ids{$id})) {
                   8578: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8579: 		} else {
                   8580: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8581: 		}
1.405     www      8582:             }
1.402     www      8583:         }
                   8584:     }
1.407     albertel 8585:     return %clicker_ids;
1.402     www      8586: }
                   8587: 
1.413     www      8588: sub clicker_grading_parameters {
                   8589:     return ('gradingmechanism' => 'scalar',
                   8590:             'upfiletype' => 'scalar',
                   8591:             'specificid' => 'scalar',
                   8592:             'pcorrect' => 'scalar',
                   8593:             'pincorrect' => 'scalar');
                   8594: }
                   8595: 
1.400     www      8596: sub process_clicker {
                   8597:     my ($r)=@_;
                   8598:     my ($symb)=&get_symb($r);
                   8599:     if (!$symb) {return '';}
                   8600:     my $result=&checkforfile_js();
                   8601:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8602:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8603:     $result.=$table;
                   8604:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8605:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.528.2.11  raeburn  8606:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
1.400     www      8607:         '.</b></td></tr>'."\n";
                   8608:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8609: # Attempt to restore parameters from last session, set defaults if not present
                   8610:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8611:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8612:                                                  \%Saveable_Parameters);
                   8613:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8614:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8615:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8616:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8617: 
                   8618:     my %checked;
1.521     www      8619:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8620:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   8621:           $checked{$gradingmechanism}="checked='checked'";
                   8622:        }
                   8623:     }
                   8624: 
1.400     www      8625:     my $upload=&mt("Upload File");
                   8626:     my $type=&mt("Type");
1.402     www      8627:     my $attendance=&mt("Award points just for participation");
                   8628:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8629:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8630:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8631:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8632:     my $pcorrect=&mt("Percentage points for correct solution");
                   8633:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8634:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8635: 						   ('iclicker' => 'i>clicker',
                   8636:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8637:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8638:     $result.=<<ENDUPFORM;
1.402     www      8639: <script type="text/javascript">
                   8640: function sanitycheck() {
                   8641: // Accept only integer percentages
                   8642:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8643:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8644: // Find out grading choice
                   8645:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8646:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8647:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8648:       }
                   8649:    }
                   8650: // By default, new choice equals user selection
                   8651:    newgradingchoice=gradingchoice;
                   8652: // Not good to give more points for false answers than correct ones
                   8653:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8654:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8655:    }
                   8656: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8657:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8658:       document.forms.gradesupload.pcorrect.value=100;
                   8659:       document.forms.gradesupload.pincorrect.value=100;
                   8660:    }
                   8661: // If the values are different, cannot be attendance only
                   8662:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8663:        (gradingchoice=='attendance')) {
                   8664:        newgradingchoice='personnel';
                   8665:    }
                   8666: // Change grading choice to new one
                   8667:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8668:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8669:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8670:       } else {
                   8671:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8672:       }
                   8673:    }
                   8674: // Remember the old state
                   8675:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8676: }
                   8677: </script>
1.400     www      8678: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8679: <input type="hidden" name="symb" value="$symb" />
                   8680: <input type="hidden" name="command" value="processclickerfile" />
                   8681: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8682: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8683: <input type="file" name="upfile" size="50" />
                   8684: <br /><label>$type: $selectform</label>
1.451     albertel 8685: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8686: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8687: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8688: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.521     www      8689: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
                   8690: <br />&nbsp;&nbsp;&nbsp;
                   8691: <input type="text" name="givenanswer" size="50" />
1.413     www      8692: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8693: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8694: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8695: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8696: </form>
                   8697: ENDUPFORM
                   8698:     $result.='</td></tr></table>'."\n".
                   8699:              '</td></tr></table><br /><br />'."\n";
                   8700:     $result.=&show_grading_menu_form($symb);
                   8701:     return $result;
                   8702: }
                   8703: 
                   8704: sub process_clicker_file {
                   8705:     my ($r)=@_;
                   8706:     my ($symb)=&get_symb($r);
                   8707:     if (!$symb) {return '';}
1.413     www      8708: 
                   8709:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8710:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8711:                                               \%Saveable_Parameters);
                   8712: 
1.400     www      8713:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8714:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8715: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8716: 	return $result.&show_grading_menu_form($symb);
1.404     www      8717:     }
1.522     www      8718:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8719:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8720:         return $result.&show_grading_menu_form($symb);
                   8721:     }
1.522     www      8722:     my $foundgiven=0;
1.521     www      8723:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8724:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8725:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8726:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8727:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8728:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8729:         $foundgiven=$#answers+1;
1.521     www      8730:     }
1.407     albertel 8731:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8732:     my %correct_ids;
1.404     www      8733:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8734: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8735:     }
                   8736:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8737: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8738: 	   $correct_id=~tr/a-z/A-Z/;
                   8739: 	   $correct_id=~s/\s//gs;
                   8740: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8741:            $correct_id=~s/[\-\:]//g;
1.414     www      8742:            if ($correct_id) {
                   8743: 	      $correct_ids{$correct_id}='specified';
                   8744:            }
                   8745:         }
1.400     www      8746:     }
1.404     www      8747:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8748: 	$result.=&mt('Score based on attendance only');
1.521     www      8749:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8750:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8751:     } else {
1.408     albertel 8752: 	my $number=0;
1.411     www      8753: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8754: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8755: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8756: 	    if ($correct_ids{$id} eq 'specified') {
                   8757: 		$result.=&mt('specified');
                   8758: 	    } else {
                   8759: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8760: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8761: 	    }
                   8762: 	    $number++;
                   8763: 	}
1.411     www      8764:         $result.="</p>\n";
1.408     albertel 8765: 	if ($number==0) {
                   8766: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8767: 	    return $result.&show_grading_menu_form($symb);
                   8768: 	}
1.404     www      8769:     }
1.405     www      8770:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8771:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8772: 		     '<span class="LC_error">',
                   8773: 		     '</span>',
                   8774: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8775:         return $result.&show_grading_menu_form($symb);
                   8776:     }
1.410     www      8777: 
                   8778: # Were able to get all the info needed, now analyze the file
                   8779: 
1.411     www      8780:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8781:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8782:     my $heading=&mt('Scanning clicker file');
                   8783:     $result.=(<<ENDHEADER);
                   8784: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8785: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8786: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8787: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8788: <input type="hidden" name="symb" value="$symb" />
                   8789: <input type="hidden" name="command" value="assignclickergrades" />
                   8790: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8791: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8792: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8793: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8794: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8795: ENDHEADER
1.522     www      8796:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8797:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8798:     } 
1.408     albertel 8799:     my %responses;
                   8800:     my @questiontitles;
1.405     www      8801:     my $errormsg='';
                   8802:     my $number=0;
                   8803:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8804: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8805:     }
1.419     www      8806:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8807:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8808:     }
1.411     www      8809:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8810:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8811:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8812:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8813:              '<br />';
1.522     www      8814:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8815:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8816:        return $result.&show_grading_menu_form($symb);
                   8817:     } 
1.414     www      8818: # Remember Question Titles
                   8819: # FIXME: Possibly need delimiter other than ":"
                   8820:     for (my $i=0;$i<$number;$i++) {
                   8821:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8822:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8823:     }
1.411     www      8824:     my $correct_count=0;
                   8825:     my $student_count=0;
                   8826:     my $unknown_count=0;
1.414     www      8827: # Match answers with usernames
                   8828: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8829:     foreach my $id (keys(%responses)) {
1.410     www      8830:        if ($correct_ids{$id}) {
1.414     www      8831:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8832:           $correct_count++;
1.410     www      8833:        } elsif ($clicker_ids{$id}) {
1.437     www      8834:           if ($clicker_ids{$id}=~/\,/) {
                   8835: # More than one user with the same clicker!
                   8836:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8837:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8838:                            "<select name='multi".$id."'>";
                   8839:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8840:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8841:              }
                   8842:              $result.='</select>';
                   8843:              $unknown_count++;
                   8844:           } else {
                   8845: # Good: found one and only one user with the right clicker
                   8846:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8847:              $student_count++;
                   8848:           }
1.410     www      8849:        } else {
1.411     www      8850:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8851:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8852:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8853:                    "\n".&mt("Domain").": ".
                   8854:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8855:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8856:           $unknown_count++;
1.410     www      8857:        }
1.405     www      8858:     }
1.412     www      8859:     $result.='<hr />'.
                   8860:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8861:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8862:        if ($correct_count==0) {
                   8863:           $errormsg.="Found no correct answers answers for grading!";
                   8864:        } elsif ($correct_count>1) {
1.414     www      8865:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8866:        }
                   8867:     }
1.428     www      8868:     if ($number<1) {
                   8869:        $errormsg.="Found no questions.";
                   8870:     }
1.412     www      8871:     if ($errormsg) {
                   8872:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8873:     } else {
                   8874:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8875:     }
                   8876:     $result.='</form></td></tr></table>'."\n".
1.410     www      8877:              '</td></tr></table><br /><br />'."\n";
1.404     www      8878:     return $result.&show_grading_menu_form($symb);
1.400     www      8879: }
                   8880: 
1.405     www      8881: sub iclicker_eval {
1.406     www      8882:     my ($questiontitles,$responses)=@_;
1.405     www      8883:     my $number=0;
                   8884:     my $errormsg='';
                   8885:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8886:         my %components=&Apache::loncommon::record_sep($line);
                   8887:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8888: 	if ($entries[0] eq 'Question') {
                   8889: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8890: 		$$questiontitles[$number]=$entries[$i];
                   8891: 		$number++;
                   8892: 	    }
                   8893: 	}
                   8894: 	if ($entries[0]=~/^\#/) {
                   8895: 	    my $id=$entries[0];
                   8896: 	    my @idresponses;
                   8897: 	    $id=~s/^[\#0]+//;
                   8898: 	    for (my $i=0;$i<$number;$i++) {
                   8899: 		my $idx=3+$i*6;
                   8900: 		push(@idresponses,$entries[$idx]);
                   8901: 	    }
                   8902: 	    $$responses{$id}=join(',',@idresponses);
                   8903: 	}
1.405     www      8904:     }
                   8905:     return ($errormsg,$number);
                   8906: }
                   8907: 
1.419     www      8908: sub interwrite_eval {
                   8909:     my ($questiontitles,$responses)=@_;
                   8910:     my $number=0;
                   8911:     my $errormsg='';
1.420     www      8912:     my $skipline=1;
                   8913:     my $questionnumber=0;
                   8914:     my %idresponses=();
1.419     www      8915:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8916:         my %components=&Apache::loncommon::record_sep($line);
                   8917:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8918:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8919:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8920:         next if $skipline;
                   8921:         if ($entries[0]!=$questionnumber) {
                   8922:            $questionnumber=$entries[0];
                   8923:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8924:            $number++;
1.419     www      8925:         }
1.420     www      8926:         my $id=$entries[4];
                   8927:         $id=~s/^[\#0]+//;
1.421     www      8928:         $id=~s/^v\d*\://i;
                   8929:         $id=~s/[\-\:]//g;
1.420     www      8930:         $idresponses{$id}[$number]=$entries[6];
                   8931:     }
1.524     raeburn  8932:     foreach my $id (keys(%idresponses)) {
1.420     www      8933:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8934:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8935:     }
                   8936:     return ($errormsg,$number);
                   8937: }
                   8938: 
1.414     www      8939: sub assign_clicker_grades {
                   8940:     my ($r)=@_;
                   8941:     my ($symb)=&get_symb($r);
                   8942:     if (!$symb) {return '';}
1.416     www      8943: # See which part we are saving to
                   8944:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8945: # FIXME: This should probably look for the first handgradeable part
                   8946:     my $part=$$partlist[0];
                   8947: # Start screen output
1.414     www      8948:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8949: 
1.414     www      8950:     my $heading=&mt('Assigning grades based on clicker file');
                   8951:     $result.=(<<ENDHEADER);
                   8952: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8953: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8954: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8955: ENDHEADER
                   8956: # Get correct result
                   8957: # FIXME: Possibly need delimiter other than ":"
                   8958:     my @correct=();
1.415     www      8959:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8960:     my $number=$env{'form.number'};
                   8961:     if ($gradingmechanism ne 'attendance') {
1.414     www      8962:        foreach my $key (keys(%env)) {
                   8963:           if ($key=~/^form\.correct\:/) {
                   8964:              my @input=split(/\,/,$env{$key});
                   8965:              for (my $i=0;$i<=$#input;$i++) {
                   8966:                  if (($correct[$i]) && ($input[$i]) &&
                   8967:                      ($correct[$i] ne $input[$i])) {
                   8968:                     $result.='<br /><span class="LC_warning">'.
                   8969:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8970:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8971:                  } elsif ($input[$i]) {
                   8972:                     $correct[$i]=$input[$i];
                   8973:                  }
                   8974:              }
                   8975:           }
                   8976:        }
1.415     www      8977:        for (my $i=0;$i<$number;$i++) {
1.414     www      8978:           if (!$correct[$i]) {
                   8979:              $result.='<br /><span class="LC_error">'.
                   8980:                       &mt('No correct result given for question "[_1]"!',
                   8981:                           $env{'form.question:'.$i}).'</span>';
                   8982:           }
                   8983:        }
                   8984:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8985:     }
                   8986: # Start grading
1.415     www      8987:     my $pcorrect=$env{'form.pcorrect'};
                   8988:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8989:     my $storecount=0;
1.415     www      8990:     foreach my $key (keys(%env)) {
1.420     www      8991:        my $user='';
1.415     www      8992:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8993:           $user=$1;
                   8994:        }
                   8995:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8996:           my $id=$1;
                   8997:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8998:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8999:           } elsif ($env{'form.multi'.$id}) {
                   9000:              $user=$env{'form.multi'.$id};
1.420     www      9001:           }
                   9002:        }
                   9003:        if ($user) { 
1.415     www      9004:           my @answer=split(/\,/,$env{$key});
                   9005:           my $sum=0;
1.522     www      9006:           my $realnumber=$number;
1.415     www      9007:           for (my $i=0;$i<$number;$i++) {
                   9008:              if ($answer[$i]) {
                   9009:                 if ($gradingmechanism eq 'attendance') {
                   9010:                    $sum+=$pcorrect;
1.522     www      9011:                 } elsif ($answer[$i] eq '*') {
                   9012:                    $sum+=$pcorrect;
                   9013:                 } elsif ($answer[$i] eq '-') {
                   9014:                    $realnumber--;
1.415     www      9015:                 } else {
                   9016:                    if ($answer[$i] eq $correct[$i]) {
                   9017:                       $sum+=$pcorrect;
                   9018:                    } else {
                   9019:                       $sum+=$pincorrect;
                   9020:                    }
                   9021:                 }
                   9022:              }
                   9023:           }
1.522     www      9024:           my $ave=$sum/(100*$realnumber);
1.416     www      9025: # Store
                   9026:           my ($username,$domain)=split(/\:/,$user);
                   9027:           my %grades=();
                   9028:           $grades{"resource.$part.solved"}='correct_by_override';
                   9029:           $grades{"resource.$part.awarded"}=$ave;
                   9030:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9031:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9032:                                                  $env{'request.course.id'},
                   9033:                                                  $domain,$username);
                   9034:           if ($returncode ne 'ok') {
                   9035:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9036:           } else {
                   9037:              $storecount++;
                   9038:           }
1.415     www      9039:        }
                   9040:     }
                   9041: # We are done
1.528.2.11  raeburn  9042:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9043:              '</td></tr></table>'."\n".
1.414     www      9044:              '</td></tr></table><br /><br />'."\n";
                   9045:     return $result.&show_grading_menu_form($symb);
                   9046: }
                   9047: 
1.1       albertel 9048: sub handler {
1.41      ng       9049:     my $request=$_[0];
1.434     albertel 9050:     &reset_caches();
1.257     albertel 9051:     if ($env{'browser.mathml'}) {
1.141     www      9052: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9053:     } else {
1.141     www      9054: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9055:     }
                   9056:     $request->send_http_header;
1.44      ng       9057:     return '' if $request->header_only;
1.41      ng       9058:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9059:     my $symb=&get_symb($request,1);
1.160     albertel 9060:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9061:     my $command=$commands[0];
1.447     foxr     9062: 
1.160     albertel 9063:     if ($#commands > 0) {
                   9064: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9065:     }
1.447     foxr     9066: 
1.513     foxr     9067:     $ssi_error = 0;
1.353     albertel 9068:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 9069:     if ($symb eq '' && $command eq '') {
1.257     albertel 9070: 	if ($env{'user.adv'}) {
                   9071: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9072: 		($env{'form.codethree'})) {
                   9073: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9074: 		    $env{'form.codethree'};
1.41      ng       9075: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9076: 		    &Apache::lonnet::checkin($token);
                   9077: 		if ($tsymb) {
1.137     albertel 9078: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9079: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9080: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9081: 					  ('grade_username' => $tuname,
                   9082: 					   'grade_domain' => $tudom,
                   9083: 					   'grade_courseid' => $tcrsid,
                   9084: 					   'grade_symb' => $tsymb)));
1.41      ng       9085: 		    } else {
1.45      ng       9086: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9087: 		    }
1.41      ng       9088: 		} else {
1.45      ng       9089: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9090: 		}
1.14      www      9091: 	    } else {
1.41      ng       9092: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9093: 	    }
                   9094: 	}
                   9095:     } else {
1.285     albertel 9096: 	&init_perm();
1.104     albertel 9097: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9098: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9099: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9100: 	    &pickStudentPage($request);
1.103     albertel 9101: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9102: 	    &displayPage($request);
1.104     albertel 9103: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9104: 	    &updateGradeByPage($request);
1.104     albertel 9105: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9106: 	    &processGroup($request);
1.104     albertel 9107: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9108: 	    $request->print(&grading_menu($request));
                   9109: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9110: 	    $request->print(&submit_options($request));
1.104     albertel 9111: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9112: 	    $request->print(&viewgrades($request));
1.104     albertel 9113: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9114: 	    $request->print(&processHandGrade($request));
1.106     albertel 9115: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9116: 	    $request->print(&editgrades($request));
1.106     albertel 9117: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9118: 	    $request->print(&verifyreceipt($request));
1.400     www      9119:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9120:             $request->print(&process_clicker($request));
                   9121:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9122:             $request->print(&process_clicker_file($request));
1.414     www      9123:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9124:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9125: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9126: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9127: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9128: 	    $request->print(&csvupload($request));
1.106     albertel 9129: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9130: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9131: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9132: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9133: 		$request->print(&csvuploadoptions($request));
1.41      ng       9134: 	    } else {
1.257     albertel 9135: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9136: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9137: 		} else {
1.257     albertel 9138: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9139: 		}
                   9140: 		$request->print(&csvuploadmap($request));
                   9141: 	    }
1.246     albertel 9142: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9143: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9144: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9145: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9146:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9147:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9148: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9149: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9150: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9151: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9152:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9153:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9154: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9155:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9156:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9157:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9158: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9159:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9160:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9161: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9162:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9163:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9164:             $request->print(&checkscantron_results($request));     
1.106     albertel 9165: 	} elsif ($command) {
1.157     albertel 9166: 	    $request->print("Access Denied ($command)");
1.26      albertel 9167: 	}
1.2       albertel 9168:     }
1.513     foxr     9169:     if ($ssi_error) {
                   9170: 	&ssi_print_error($request);
                   9171:     }
1.353     albertel 9172:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9173:     &reset_caches();
1.44      ng       9174:     return '';
                   9175: }
                   9176: 
1.1       albertel 9177: 1;
                   9178: 
1.13      albertel 9179: __END__;

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