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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.598   ! www         4: # $Id: grades.pm,v 1.597 2010/03/11 16:29:42 wenzelju Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.170     albertel   46: use String::Similarity;
1.359     www        47: use LONCAPA;
                     48: 
1.315     bowersj2   49: use POSIX qw(floor);
1.87      www        50: 
1.435     foxr       51: 
1.513     foxr       52: 
1.435     foxr       53: my %perm=();
1.447     foxr       54: 
1.513     foxr       55: #  These variables are used to recover from ssi errors
                     56: 
                     57: my $ssi_retries = 5;
                     58: my $ssi_error;
                     59: my $ssi_error_resource;
                     60: my $ssi_error_message;
                     61: 
                     62: 
                     63: sub ssi_with_retries {
                     64:     my ($resource, $retries, %form) = @_;
                     65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     66:     if ($response->is_error) {
                     67: 	$ssi_error          = 1;
                     68: 	$ssi_error_resource = $resource;
                     69: 	$ssi_error_message  = $response->code . " " . $response->message;
                     70:     }
                     71: 
                     72:     return $content;
                     73: 
                     74: }
                     75: #
                     76: #  Prodcuces an ssi retry failure error message to the user:
                     77: #
                     78: 
                     79: sub ssi_print_error {
                     80:     my ($r) = @_;
1.516     raeburn    81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     82:     $r->print('
                     83: <br />
                     84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     85: <p>
                     86: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     88: '.&mt('Error:').' '.$ssi_error_message.'
                     89: </p>
                     90: <p>'.
                     91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     93: '</p>');
                     94:     return;
1.513     foxr       95: }
                     96: 
1.44      ng         97: #
1.146     albertel   98: # --- Retrieve the parts from the metadata file.---
1.598   ! www        99: # Returns an array of everything that the resources stores away
        !           100: #
        !           101: 
1.44      ng        102: sub getpartlist {
1.582     raeburn   103:     my ($symb,$errorref) = @_;
1.439     albertel  104: 
                    105:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   106:     unless (ref($navmap)) {
                    107:         if (ref($errorref)) { 
                    108:             $$errorref = 'navmap';
                    109:             return;
                    110:         }
                    111:     }
1.439     albertel  112:     my $res      = $navmap->getBySymb($symb);
                    113:     my $partlist = $res->parts();
                    114:     my $url      = $res->src();
                    115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    116: 
1.146     albertel  117:     my @stores;
1.439     albertel  118:     foreach my $part (@{ $partlist }) {
1.146     albertel  119: 	foreach my $key (@metakeys) {
                    120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    121: 	}
                    122:     }
                    123:     return @stores;
1.2       albertel  124: }
                    125: 
1.44      ng        126: # --- Get the symbolic name of a problem and the url
1.598   ! www       127: # Generate an error message if symb could not be found unless silent flag is set
        !           128: # Takes $env{'form.symb'} by default; if not present, takes $env{'form.url'} and tries to get symb from that
        !           129: #
        !           130:  
1.324     albertel  131: sub get_symb {
1.173     albertel  132:     my ($request,$silent) = @_;
1.257     albertel  133:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    134:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  135:     if ($symb eq '') { 
                    136: 	if (!$silent) {
1.598   ! www       137: 	    $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
1.173     albertel  138: 	    return ();
                    139: 	}
                    140:     }
1.418     albertel  141:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  142:     return ($symb);
1.32      ng        143: }
                    144: 
1.129     ng        145: #--- Format fullname, username:domain if different for display
                    146: #--- Use anywhere where the student names are listed
                    147: sub nameUserString {
                    148:     my ($type,$fullname,$uname,$udom) = @_;
                    149:     if ($type eq 'header') {
1.485     albertel  150: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        151:     } else {
1.398     albertel  152: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    153: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        154:     }
                    155: }
                    156: 
1.44      ng        157: #--- Get the partlist and the response type for a given problem. ---
                    158: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        159: sub response_type {
1.582     raeburn   160:     my ($symb,$response_error) = @_;
1.377     albertel  161: 
                    162:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   163:     unless (ref($navmap)) {
                    164:         if (ref($response_error)) {
                    165:             $$response_error = 1;
                    166:         }
                    167:         return;
                    168:     }
1.377     albertel  169:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   170:     unless (ref($res)) {
                    171:         $$response_error = 1;
                    172:         return;
                    173:     }
1.377     albertel  174:     my $partlist = $res->parts();
1.392     albertel  175:     my %vPart = 
                    176: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  177:     my (%response_types,%handgrade);
                    178:     foreach my $part (@{ $partlist }) {
1.392     albertel  179: 	next if (%vPart && !exists($vPart{$part}));
                    180: 
1.377     albertel  181: 	my @types = $res->responseType($part);
                    182: 	my @ids = $res->responseIds($part);
                    183: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    184: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    185: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    186: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    187: 				     '.handgrade',$symb);
1.41      ng        188: 	}
                    189:     }
1.377     albertel  190:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        191: }
                    192: 
1.375     albertel  193: sub flatten_responseType {
                    194:     my ($responseType) = @_;
                    195:     my @part_response_id =
                    196: 	map { 
                    197: 	    my $part = $_;
                    198: 	    map {
                    199: 		[$part,$_]
                    200: 		} sort(keys(%{ $responseType->{$part} }));
                    201: 	} sort(keys(%$responseType));
                    202:     return @part_response_id;
                    203: }
                    204: 
1.207     albertel  205: sub get_display_part {
1.324     albertel  206:     my ($partID,$symb)=@_;
1.207     albertel  207:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    208:     if (defined($display) and $display ne '') {
1.577     bisitz    209:         $display.= ' (<span class="LC_internal_info">'
                    210:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  211:     } else {
                    212: 	$display=$partID;
                    213:     }
                    214:     return $display;
                    215: }
1.269     raeburn   216: 
1.118     ng        217: #--- Show resource title
                    218: #--- and parts and response type
1.598   ! www       219: #sub showResourceInfo {
        !           220: #    my ($symb,$probTitle,$checkboxes,$res_error) = @_;
        !           221: #    my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
        !           222: #    my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
        !           223: #    if (ref($res_error)) {
        !           224: #        if ($$res_error) {
        !           225: #            return;
        !           226: #        }
        !           227: #    }
        !           228: #    $result.=&Apache::loncommon::start_data_table()
        !           229: #            .&Apache::loncommon::start_data_table_header_row();
        !           230: #    if ($checkboxes) {
        !           231: #        $result.='<th>&nbsp;</th>';
        !           232: #    }
        !           233: #    $result.='<th>'.&mt('Problem Part').'</th>'
        !           234: #            .'<th>'.&mt('Res. ID').'</th>'
        !           235: #            .'<th>'.&mt('Type').'</th>'
        !           236: #            .&Apache::loncommon::end_data_table_header_row();
        !           237: #    my %resptype = ();
        !           238: #    my $hdgrade='no';
        !           239: #    my %partsseen;
        !           240: #    foreach my $partID (sort(keys(%$responseType))) {
        !           241: #        foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
        !           242: #            my $handgrade=$$handgrade{$partID.'_'.$resID};
        !           243: #            my $responsetype = $responseType->{$partID}->{$resID};
        !           244: #            $hdgrade = $handgrade if ($handgrade eq 'yes');
        !           245: #            $result.=&Apache::loncommon::start_data_table_row();
        !           246: #            if ($checkboxes) {
        !           247: #                if (exists($partsseen{$partID})) {
        !           248: #                    $result.="<td>&nbsp;</td>";
        !           249: #                } else {
        !           250: #                    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
        !           251: #                }
        !           252: #                $partsseen{$partID}=1;
        !           253: #            }
        !           254: #            my $display_part=&get_display_part($partID,$symb);
        !           255: #            $result.='<td>'.$display_part.'</td>'
        !           256: #                    .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
        !           257: #                    .'<td>'.&mt($responsetype).'</td>'
1.584     bisitz    258: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
1.598   ! www       259: #                    .&Apache::loncommon::end_data_table_row();
        !           260: #       }
        !           261: #    }
        !           262: #    $result.=&Apache::loncommon::end_data_table();
        !           263: #    return $result,$responseType,$hdgrade,$partlist,$handgrade;
        !           264: #}
1.118     ng        265: 
1.434     albertel  266: sub reset_caches {
                    267:     &reset_analyze_cache();
                    268:     &reset_perm();
                    269: }
                    270: 
                    271: {
                    272:     my %analyze_cache;
1.557     raeburn   273:     my %analyze_cache_formkeys;
1.148     albertel  274: 
1.434     albertel  275:     sub reset_analyze_cache {
                    276: 	undef(%analyze_cache);
1.557     raeburn   277:         undef(%analyze_cache_formkeys);
1.434     albertel  278:     }
                    279: 
                    280:     sub get_analyze {
1.557     raeburn   281: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  282: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   283: 	if (exists($analyze_cache{$key})) {
                    284:             my $getupdate = 0;
                    285:             if (ref($add_to_hash) eq 'HASH') {
                    286:                 foreach my $item (keys(%{$add_to_hash})) {
                    287:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    288:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    289:                             $getupdate = 1;
                    290:                             last;
                    291:                         }
                    292:                     } else {
                    293:                         $getupdate = 1;
                    294:                     }
                    295:                 }
                    296:             }
                    297:             if (!$getupdate) {
                    298:                 return $analyze_cache{$key};
                    299:             }
                    300:         }
1.434     albertel  301: 
                    302: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    303: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   304:         my %form = ('grade_target'      => 'analyze',
                    305:                     'grade_domain'      => $udom,
                    306:                     'grade_symb'        => $symb,
                    307:                     'grade_courseid'    =>  $env{'request.course.id'},
                    308:                     'grade_username'    => $uname,
                    309:                     'grade_noincrement' => $no_increment);
                    310:         if (ref($add_to_hash)) {
                    311:             %form = (%form,%{$add_to_hash});
                    312:         } 
                    313: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  314: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    315: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   316:         if (ref($add_to_hash) eq 'HASH') {
                    317:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    318:         } else {
                    319:             $analyze_cache_formkeys{$key} = {};
                    320:         }
1.434     albertel  321: 	return $analyze_cache{$key} = \%analyze;
                    322:     }
                    323: 
                    324:     sub get_order {
1.525     raeburn   325: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    326: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  327: 	return $analyze->{"$partid.$respid.shown"};
                    328:     }
                    329: 
                    330:     sub get_radiobutton_correct_foil {
                    331: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    332: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   333:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    334:         if (ref($foils) eq 'ARRAY') {
                    335: 	    foreach my $foil (@{$foils}) {
                    336: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    337: 		    return $foil;
                    338: 	        }
1.434     albertel  339: 	    }
                    340: 	}
                    341:     }
1.554     raeburn   342: 
                    343:     sub scantron_partids_tograde {
1.557     raeburn   344:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   345:         my (%analysis,@parts);
                    346:         if (ref($resource)) {
                    347:             my $symb = $resource->symb();
1.557     raeburn   348:             my $add_to_form;
                    349:             if ($check_for_randomlist) {
                    350:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    351:             }
                    352:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   353:             if (ref($analyze) eq 'HASH') {
                    354:                 %analysis = %{$analyze};
                    355:             }
                    356:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    357:                 foreach my $part (@{$analysis{'parts'}}) {
                    358:                     my ($id,$respid) = split(/\./,$part);
                    359:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    360:                         push(@parts,$part);
                    361:                     }
                    362:                 }
                    363:             }
                    364:         }
                    365:         return (\%analysis,\@parts);
                    366:     }
                    367: 
1.148     albertel  368: }
1.434     albertel  369: 
1.118     ng        370: #--- Clean response type for display
1.335     albertel  371: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    372: #        response types only.
1.118     ng        373: sub cleanRecord {
1.336     albertel  374:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    375: 	$uname,$udom) = @_;
1.398     albertel  376:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  377:     if ($response =~ /^(option|rank)$/) {
                    378: 	my %answer=&Apache::lonnet::str2hash($answer);
                    379: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    380: 	my ($toprow,$bottomrow);
                    381: 	foreach my $foil (@$order) {
                    382: 	    if ($grading{$foil} == 1) {
                    383: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    384: 	    } else {
                    385: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    386: 	    }
1.398     albertel  387: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  388: 	}
                    389: 	return '<blockquote><table border="1">'.
1.466     albertel  390: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    391: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  392: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    393:     } elsif ($response eq 'match') {
                    394: 	my %answer=&Apache::lonnet::str2hash($answer);
                    395: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    396: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    397: 	my ($toprow,$middlerow,$bottomrow);
                    398: 	foreach my $foil (@$order) {
                    399: 	    my $item=shift(@items);
                    400: 	    if ($grading{$foil} == 1) {
                    401: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  402: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  403: 	    } else {
                    404: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  405: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  406: 	    }
1.398     albertel  407: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        408: 	}
1.126     ng        409: 	return '<blockquote><table border="1">'.
1.466     albertel  410: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    411: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  412: 	    $middlerow.'</tr>'.
1.466     albertel  413: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  414: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    415:     } elsif ($response eq 'radiobutton') {
                    416: 	my %answer=&Apache::lonnet::str2hash($answer);
                    417: 	my ($toprow,$bottomrow);
1.434     albertel  418: 	my $correct = 
                    419: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    420: 	foreach my $foil (@$order) {
1.148     albertel  421: 	    if (exists($answer{$foil})) {
1.434     albertel  422: 		if ($foil eq $correct) {
1.466     albertel  423: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  424: 		} else {
1.466     albertel  425: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  426: 		}
                    427: 	    } else {
1.466     albertel  428: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  429: 	    }
1.398     albertel  430: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  431: 	}
                    432: 	return '<blockquote><table border="1">'.
1.466     albertel  433: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    434: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  435: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  436:     } elsif ($response eq 'essay') {
1.257     albertel  437: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        438: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  439: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    440: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        441: 
1.257     albertel  442: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    443: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    444: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    445: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    446: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    447: 	    $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        448: 	}
1.166     albertel  449: 	$answer =~ s-\n-<br />-g;
                    450: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  451:     } elsif ( $response eq 'organic') {
                    452: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    453: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    454: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    455: 	return $result;
1.335     albertel  456:     } elsif ( $response eq 'Task') {
                    457: 	if ( $answer eq 'SUBMITTED') {
                    458: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  459: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  460: 	    return $result;
                    461: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    462: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    463: 			       keys(%{$record}));
                    464: 	    return join('<br />',($version,@matches));
                    465: 			       
                    466: 			       
                    467: 	} else {
                    468: 	    my $result =
                    469: 		'<p>'
                    470: 		.&mt('Overall result: [_1]',
                    471: 		     $record->{$version."resource.$respid.$partid.status"})
                    472: 		.'</p>';
                    473: 	    
                    474: 	    $result .= '<ul>';
                    475: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    476: 			     keys(%{$record}));
                    477: 	    foreach my $grade (sort(@grade)) {
                    478: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    479: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    480: 				     $dim, $record->{$grade}).
                    481: 			  '</li>';
                    482: 	    }
                    483: 	    $result.='</ul>';
                    484: 	    return $result;
                    485: 	}
1.440     albertel  486:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    487: 	$answer = 
                    488: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    489: 							      $answer);
1.122     ng        490:     }
1.118     ng        491:     return $answer;
                    492: }
                    493: 
                    494: #-- A couple of common js functions
                    495: sub commonJSfunctions {
                    496:     my $request = shift;
1.597     wenzelju  497:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        498:     function radioSelection(radioButton) {
                    499: 	var selection=null;
                    500: 	if (radioButton.length > 1) {
                    501: 	    for (var i=0; i<radioButton.length; i++) {
                    502: 		if (radioButton[i].checked) {
                    503: 		    return radioButton[i].value;
                    504: 		}
                    505: 	    }
                    506: 	} else {
                    507: 	    if (radioButton.checked) return radioButton.value;
                    508: 	}
                    509: 	return selection;
                    510:     }
                    511: 
                    512:     function pullDownSelection(selectOne) {
                    513: 	var selection="";
                    514: 	if (selectOne.length > 1) {
                    515: 	    for (var i=0; i<selectOne.length; i++) {
                    516: 		if (selectOne[i].selected) {
                    517: 		    return selectOne[i].value;
                    518: 		}
                    519: 	    }
                    520: 	} else {
1.138     albertel  521:             // only one value it must be the selected one
                    522: 	    return selectOne.value;
1.118     ng        523: 	}
                    524:     }
                    525: COMMONJSFUNCTIONS
                    526: }
                    527: 
1.44      ng        528: #--- Dumps the class list with usernames,list of sections,
                    529: #--- section, ids and fullnames for each user.
                    530: sub getclasslist {
1.449     banghart  531:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  532:     my @getsec;
1.450     banghart  533:     my @getgroup;
1.442     banghart  534:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  535:     if (!ref($getsec)) {
                    536: 	if ($getsec ne '' && $getsec ne 'all') {
                    537: 	    @getsec=($getsec);
                    538: 	}
                    539:     } else {
                    540: 	@getsec=@{$getsec};
                    541:     }
                    542:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  543:     if (!ref($getgroup)) {
                    544: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    545: 	    @getgroup=($getgroup);
                    546: 	}
                    547:     } else {
                    548: 	@getgroup=@{$getgroup};
                    549:     }
                    550:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  551: 
1.449     banghart  552:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  553:     # Bail out if we were unable to get the classlist
1.56      matthew   554:     return if (! defined($classlist));
1.449     banghart  555:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   556:     #
                    557:     my %sections;
                    558:     my %fullnames;
1.205     matthew   559:     foreach my $student (keys(%$classlist)) {
                    560:         my $end      = 
                    561:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    562:         my $start    = 
                    563:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    564:         my $id       = 
                    565:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    566:         my $section  = 
                    567:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    568:         my $fullname = 
                    569:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    570:         my $status   = 
                    571:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  572:         my $group   = 
                    573:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        574: 	# filter students according to status selected
1.442     banghart  575: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    576: 	    if (!($stu_status =~ $status)) {
1.450     banghart  577: 		delete($classlist->{$student});
1.76      ng        578: 		next;
                    579: 	    }
                    580: 	}
1.450     banghart  581: 	# filter students according to groups selected
1.453     banghart  582: 	my @stu_groups = split(/,/,$group);
1.450     banghart  583: 	if (@getgroup) {
                    584: 	    my $exclude = 1;
1.454     banghart  585: 	    foreach my $grp (@getgroup) {
                    586: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  587: 	            if ($stu_group eq $grp) {
                    588: 	                $exclude = 0;
                    589:     	            } 
1.450     banghart  590: 	        }
1.453     banghart  591:     	        if (($grp eq 'none') && !$group) {
                    592:         	        $exclude = 0;
                    593:         	}
1.450     banghart  594: 	    }
                    595: 	    if ($exclude) {
                    596: 	        delete($classlist->{$student});
                    597: 	    }
                    598: 	}
1.205     matthew   599: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  600: 	if (&canview($section)) {
1.291     albertel  601: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  602: 		$sections{$section}++;
1.450     banghart  603: 		if ($classlist->{$student}) {
                    604: 		    $fullnames{$student}=$fullname;
                    605: 		}
1.103     albertel  606: 	    } else {
1.205     matthew   607: 		delete($classlist->{$student});
1.103     albertel  608: 	    }
                    609: 	} else {
1.205     matthew   610: 	    delete($classlist->{$student});
1.103     albertel  611: 	}
1.44      ng        612:     }
                    613:     my %seen = ();
1.56      matthew   614:     my @sections = sort(keys(%sections));
                    615:     return ($classlist,\@sections,\%fullnames);
1.44      ng        616: }
                    617: 
1.103     albertel  618: sub canmodify {
                    619:     my ($sec)=@_;
                    620:     if ($perm{'mgr'}) {
                    621: 	if (!defined($perm{'mgr_section'})) {
                    622: 	    # can modify whole class
                    623: 	    return 1;
                    624: 	} else {
                    625: 	    if ($sec eq $perm{'mgr_section'}) {
                    626: 		#can modify the requested section
                    627: 		return 1;
                    628: 	    } else {
                    629: 		# can't modify the request section
                    630: 		return 0;
                    631: 	    }
                    632: 	}
                    633:     }
                    634:     #can't modify
                    635:     return 0;
                    636: }
                    637: 
                    638: sub canview {
                    639:     my ($sec)=@_;
                    640:     if ($perm{'vgr'}) {
                    641: 	if (!defined($perm{'vgr_section'})) {
                    642: 	    # can modify whole class
                    643: 	    return 1;
                    644: 	} else {
                    645: 	    if ($sec eq $perm{'vgr_section'}) {
                    646: 		#can modify the requested section
                    647: 		return 1;
                    648: 	    } else {
                    649: 		# can't modify the request section
                    650: 		return 0;
                    651: 	    }
                    652: 	}
                    653:     }
                    654:     #can't modify
                    655:     return 0;
                    656: }
                    657: 
1.44      ng        658: #--- Retrieve the grade status of a student for all the parts
                    659: sub student_gradeStatus {
1.324     albertel  660:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  661:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        662:     my %partstatus = ();
                    663:     foreach (@$partlist) {
1.128     ng        664: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        665: 	$status              = 'nothing' if ($status eq '');
                    666: 	$partstatus{$_}      = $status;
                    667: 	my $subkey           = "resource.$_.submitted_by";
                    668: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    669:     }
                    670:     return %partstatus;
                    671: }
                    672: 
1.45      ng        673: # hidden form and javascript that calls the form
                    674: # Use by verifyscript and viewgrades
                    675: # Shows a student's view of problem and submission
                    676: sub jscriptNform {
1.324     albertel  677:     my ($symb) = @_;
1.442     banghart  678:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  679:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        680: 	'    function viewOneStudent(user,domain) {'."\n".
                    681: 	'	document.onestudent.student.value = user;'."\n".
                    682: 	'	document.onestudent.userdom.value = domain;'."\n".
                    683: 	'	document.onestudent.submit();'."\n".
                    684: 	'    }'."\n".
1.597     wenzelju  685: 	"\n");
1.45      ng        686:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  687: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  688: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    689: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  690: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        691: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    692: 	'<input type="hidden" name="student" value="" />'."\n".
                    693: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    694: 	'</form>'."\n";
                    695:     return $jscript;
                    696: }
1.39      ng        697: 
1.447     foxr      698: 
                    699: 
1.315     bowersj2  700: # Given the score (as a number [0-1] and the weight) what is the final
                    701: # point value? This function will round to the nearest tenth, third,
                    702: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  703: sub compute_points {
1.315     bowersj2  704:     my ($score, $weight) = @_;
                    705:     
                    706:     my $tolerance = .00001;
                    707:     my $points = $score * $weight;
                    708: 
                    709:     # Check for nearness to 1/x.
                    710:     my $check_for_nearness = sub {
                    711:         my ($factor) = @_;
                    712:         my $num = ($points * $factor) + $tolerance;
                    713:         my $floored_num = floor($num);
1.316     albertel  714:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  715:             return $floored_num / $factor;
                    716:         }
                    717:         return $points;
                    718:     };
                    719: 
                    720:     $points = $check_for_nearness->(10);
                    721:     $points = $check_for_nearness->(3);
                    722:     $points = $check_for_nearness->(4);
                    723:     
                    724:     return $points;
                    725: }
                    726: 
1.44      ng        727: #------------------ End of general use routines --------------------
1.87      www       728: 
                    729: #
                    730: # Find most similar essay
                    731: #
                    732: 
                    733: sub most_similar {
1.426     albertel  734:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       735: 
                    736: # ignore spaces and punctuation
                    737: 
                    738:     $uessay=~s/\W+/ /gs;
                    739: 
1.282     www       740: # ignore empty submissions (occuring when only files are sent)
                    741: 
1.598   ! www       742:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       743: 
1.87      www       744: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       745:     my $limit=0.6;
1.87      www       746:     my $sname='';
                    747:     my $sdom='';
                    748:     my $scrsid='';
                    749:     my $sessay='';
                    750: # go through all essays ...
1.426     albertel  751:     foreach my $tkey (keys(%$old_essays)) {
                    752: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       753: # ... except the same student
1.426     albertel  754:         next if (($tname eq $uname) && ($tdom eq $udom));
                    755: 	my $tessay=$old_essays->{$tkey};
                    756: 	$tessay=~s/\W+/ /gs;
1.87      www       757: # String similarity gives up if not even limit
1.426     albertel  758: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       759: # Found one
1.426     albertel  760: 	if ($tsimilar>$limit) {
                    761: 	    $limit=$tsimilar;
                    762: 	    $sname=$tname;
                    763: 	    $sdom=$tdom;
                    764: 	    $scrsid=$tcrsid;
                    765: 	    $sessay=$old_essays->{$tkey};
                    766: 	}
1.87      www       767:     }
1.88      www       768:     if ($limit>0.6) {
1.87      www       769:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    770:     } else {
                    771:        return ('','','','',0);
                    772:     }
                    773: }
                    774: 
1.44      ng        775: #-------------------------------------------------------------------
                    776: 
                    777: #------------------------------------ Receipt Verification Routines
1.45      ng        778: #
1.44      ng        779: #--- Check whether a receipt number is valid.---
                    780: sub verifyreceipt {
                    781:     my $request  = shift;
                    782: 
1.257     albertel  783:     my $courseid = $env{'request.course.id'};
1.184     www       784:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  785: 	$env{'form.receipt'};
1.44      ng        786:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  787:     my ($symb)   = &get_symb($request);
1.44      ng        788: 
1.487     albertel  789:     my $title.=
                    790: 	'<h3><span class="LC_info">'.
1.584     bisitz    791: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  792: 	'</span></h3>'."\n".
                    793: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    794: 	'</h4>'."\n";
1.44      ng        795: 
                    796:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   797:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  798:     
                    799:     my $receiptparts=0;
1.390     albertel  800:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    801: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  802:     my $parts=['0'];
1.582     raeburn   803:     if ($receiptparts) {
                    804:         my $res_error; 
                    805:         ($parts)=&response_type($symb,\$res_error);
                    806:         if ($res_error) {
                    807:             return &navmap_errormsg();
                    808:         } 
                    809:     }
1.486     albertel  810:     
                    811:     my $header = 
                    812: 	&Apache::loncommon::start_data_table().
                    813: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  814: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    815: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    816: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  817:     if ($receiptparts) {
1.487     albertel  818: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  819:     }
                    820:     $header.=
                    821: 	&Apache::loncommon::end_data_table_header_row();
                    822: 
1.294     albertel  823:     foreach (sort 
                    824: 	     {
                    825: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    826: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    827: 		 }
                    828: 		 return $a cmp $b;
                    829: 	     } (keys(%$fullname))) {
1.44      ng        830: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  831: 	foreach my $part (@$parts) {
                    832: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  833: 		$contents.=
                    834: 		    &Apache::loncommon::start_data_table_row().
                    835: 		    '<td>&nbsp;'."\n".
1.177     albertel  836: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  837: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  838: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    839: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    840: 		if ($receiptparts) {
                    841: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    842: 		}
1.486     albertel  843: 		$contents.= 
                    844: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  845: 		
                    846: 		$matches++;
                    847: 	    }
1.44      ng        848: 	}
                    849:     }
                    850:     if ($matches == 0) {
1.584     bisitz    851:         $string = $title
                    852:                  .'<p class="LC_warning">'
                    853:                  .&mt('No match found for the above receipt number.')
                    854:                  .'</p>';
1.44      ng        855:     } else {
1.324     albertel  856: 	$string = &jscriptNform($symb).$title.
1.487     albertel  857: 	    '<p>'.
1.584     bisitz    858: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  859: 	    '</p>'.
1.486     albertel  860: 	    $header.
                    861: 	    $contents.
                    862: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        863:     }
1.324     albertel  864:     return $string.&show_grading_menu_form($symb);
1.44      ng        865: }
                    866: 
                    867: #--- This is called by a number of programs.
                    868: #--- Called from the Grading Menu - View/Grade an individual student
                    869: #--- Also called directly when one clicks on the subm button 
                    870: #    on the problem page.
1.30      ng        871: sub listStudents {
1.41      ng        872:     my ($request) = shift;
1.49      albertel  873: 
1.324     albertel  874:     my ($symb) = &get_symb($request);
1.257     albertel  875:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    876:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    877:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  878:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  879:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    880:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  881:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    882: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  883: 
1.548     bisitz    884:     my $result='<h3><span class="LC_info">&nbsp;'
                    885: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  886: 	.'</span></h3>';
1.118     ng        887: 
1.598   ! www       888: #    my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
        !           889:     my ($partlist,$handgrade,$responseType) = &response_type($symb
        !           890: #,$res_error
        !           891:     );
1.49      albertel  892: 
1.559     raeburn   893:     my %lt = &Apache::lonlocal::texthash (
                    894: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    895: 		'single'   => 'Please select the student before clicking on the Next button.',
                    896: 	     );
1.597     wenzelju  897:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        898:     function checkSelect(checkBox) {
                    899: 	var ctr=0;
                    900: 	var sense="";
                    901: 	if (checkBox.length > 1) {
                    902: 	    for (var i=0; i<checkBox.length; i++) {
                    903: 		if (checkBox[i].checked) {
                    904: 		    ctr++;
                    905: 		}
                    906: 	    }
1.485     albertel  907: 	    sense = '$lt{'multiple'}';
1.110     ng        908: 	} else {
                    909: 	    if (checkBox.checked) {
                    910: 		ctr = 1;
                    911: 	    }
1.485     albertel  912: 	    sense = '$lt{'single'}';
1.110     ng        913: 	}
                    914: 	if (ctr == 0) {
1.485     albertel  915: 	    alert(sense);
1.110     ng        916: 	    return false;
                    917: 	}
                    918: 	document.gradesub.submit();
                    919:     }
                    920: 
                    921:     function reLoadList(formname) {
1.112     ng        922: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        923: 	formname.command.value = 'submission';
                    924: 	formname.submit();
                    925:     }
1.45      ng        926: LISTJAVASCRIPT
                    927: 
1.118     ng        928:     &commonJSfunctions($request);
1.41      ng        929:     $request->print($result);
1.39      ng        930: 
1.401     albertel  931:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    932:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  933:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598   ! www       934: 	"\n";
1.485     albertel  935: 	
1.561     bisitz    936:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    937:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    938:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    939:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    940:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    941:                   .&Apache::lonhtmlcommon::row_closure();
                    942:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    943:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    944:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    945:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    946:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  947: 
                    948:     my $submission_options;
1.257     albertel  949:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  950: 	$submission_options.=
                    951: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  952:     }
1.442     banghart  953:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    954:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  955:     $env{'form.Status'} = $saveStatus;
1.485     albertel  956:     $submission_options.=
1.592     bisitz    957:         '<span class="LC_nobreak">'.
                    958:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    959:         &mt('last submission only').' </label></span>'."\n".
                    960:         '<span class="LC_nobreak">'.
                    961:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    962:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    963:         '<span class="LC_nobreak">'.
                    964:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    965:         &mt('by dates and submissions').'</label></span>'."\n".
                    966:         '<span class="LC_nobreak">'.
                    967:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    968:         &mt('all details').'</label></span>';
1.561     bisitz    969:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    970:                   .$submission_options
                    971:                   .&Apache::lonhtmlcommon::row_closure();
                    972: 
                    973:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    974:                   .'<select name="increment">'
                    975:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    976:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    977:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    978:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    979:                   .'</select>'
                    980:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  981: 
                    982:     $gradeTable .= 
1.432     banghart  983:         &build_section_inputs().
1.45      ng        984: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  985: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    986: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    987: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    988: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  989: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        990: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    991: 
1.257     albertel  992:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    993: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        994:     } else {
1.561     bisitz    995:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    996:                       .&Apache::lonhtmlcommon::StatusOptions(
                    997:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    998:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        999:     }
1.112     ng       1000: 
1.561     bisitz   1001:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1002:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1003:                   .&Apache::lonhtmlcommon::row_closure(1)
                   1004:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1005: 
                   1006:     $gradeTable .= '<p>'
                   1007:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
                   1008:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1009:                   .'</p>';
1.249     albertel 1010: 
                   1011: # checkall buttons
                   1012:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1013:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1014:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1015:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1016:     $gradeTable.=&check_buttons();
1.450     banghart 1017:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1018:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1019: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1020:     my $loop = 0;
                   1021:     while ($loop < 2) {
1.485     albertel 1022: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1023: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1024: 	if ($env{'form.showgrading'} eq 'yes' 
                   1025: 	    && $submitonly ne 'queued'
                   1026: 	    && $submitonly ne 'all') {
1.485     albertel 1027: 	    foreach my $part (sort(@$partlist)) {
                   1028: 		my $display_part=
                   1029: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1030: 		$gradeTable.=
                   1031: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1032: 	    }
1.301     albertel 1033: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1034: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1035: 	}
                   1036: 	$loop++;
1.126     ng       1037: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1038:     }
1.474     albertel 1039:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1040: 
1.45      ng       1041:     my $ctr = 0;
1.294     albertel 1042:     foreach my $student (sort 
                   1043: 			 {
                   1044: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1045: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1046: 			     }
                   1047: 			     return $a cmp $b;
                   1048: 			 }
                   1049: 			 (keys(%$fullname))) {
1.41      ng       1050: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1051: 
1.110     ng       1052: 	my %status = ();
1.301     albertel 1053: 
                   1054: 	if ($submitonly eq 'queued') {
                   1055: 	    my %queue_status = 
                   1056: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1057: 							$udom,$uname);
                   1058: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1059: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1060: 	}
                   1061: 
                   1062: 	if ($env{'form.showgrading'} eq 'yes' 
                   1063: 	    && $submitonly ne 'queued'
                   1064: 	    && $submitonly ne 'all') {
1.324     albertel 1065: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1066: 	    my $submitted = 0;
1.164     albertel 1067: 	    my $graded = 0;
1.248     albertel 1068: 	    my $incorrect = 0;
1.110     ng       1069: 	    foreach (keys(%status)) {
1.145     albertel 1070: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1071: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1072: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1073: 		
1.110     ng       1074: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1075: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1076: 		    $submitted = 0;
1.150     albertel 1077: 		    my ($part)=split(/\./,$partid);
1.110     ng       1078: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1079: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1080: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1081: 		}
1.41      ng       1082: 	    }
1.248     albertel 1083: 	    
1.156     albertel 1084: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1085: 				     $submitonly eq 'incorrect' ||
                   1086: 				     $submitonly eq 'graded'));
1.248     albertel 1087: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1088: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1089: 	}
1.34      ng       1090: 
1.45      ng       1091: 	$ctr++;
1.249     albertel 1092: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1093:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1094: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1095: 	    if ($ctr%2 ==1) {
                   1096: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1097: 	    }
1.126     ng       1098: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1099:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1100:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1101: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1102: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1103: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1104: 
1.257     albertel 1105: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1106: 		foreach (sort(keys(%status))) {
1.485     albertel 1107: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1108: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1109: 		}
1.41      ng       1110: 	    }
1.126     ng       1111: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1112: 	    if ($ctr%2 ==0) {
                   1113: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1114: 	    }
1.41      ng       1115: 	}
                   1116:     }
1.110     ng       1117:     if ($ctr%2 ==1) {
1.126     ng       1118: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1119: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1120: 		&& $submitonly ne 'queued'
                   1121: 		&& $submitonly ne 'all') {
1.110     ng       1122: 		foreach (@$partlist) {
                   1123: 		    $gradeTable.='<td>&nbsp;</td>';
                   1124: 		}
1.301     albertel 1125: 	    } elsif ($submitonly eq 'queued') {
                   1126: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1127: 	    }
1.474     albertel 1128: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1129:     }
                   1130: 
1.474     albertel 1131:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1132:         '<input type="button" '.
                   1133:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1134:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1135:     if ($ctr == 0) {
1.96      albertel 1136: 	my $num_students=(scalar(keys(%$fullname)));
                   1137: 	if ($num_students eq 0) {
1.485     albertel 1138: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1139: 	} else {
1.171     albertel 1140: 	    my $submissions='submissions';
                   1141: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1142: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1143: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1144: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1145: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1146: 		    $num_students).
                   1147: 		'</span><br />';
1.96      albertel 1148: 	}
1.46      ng       1149:     } elsif ($ctr == 1) {
1.474     albertel 1150: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1151:     }
1.324     albertel 1152:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1153:     $request->print($gradeTable);
1.44      ng       1154:     return '';
1.10      ng       1155: }
                   1156: 
1.44      ng       1157: #---- Called from the listStudents routine
1.249     albertel 1158: 
                   1159: sub check_script {
                   1160:     my ($form, $type)=@_;
1.597     wenzelju 1161:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1162:     function checkall() {
                   1163:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1164:             ele = document.forms.'.$form.'.elements[i];
                   1165:             if (ele.name == "'.$type.'") {
                   1166:             document.forms.'.$form.'.elements[i].checked=true;
                   1167:                                        }
                   1168:         }
                   1169:     }
                   1170: 
                   1171:     function checksec() {
                   1172:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1173:             ele = document.forms.'.$form.'.elements[i];
                   1174:            string = document.forms.'.$form.'.chksec.value;
                   1175:            if
                   1176:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1177:               document.forms.'.$form.'.elements[i].checked=true;
                   1178:             }
                   1179:         }
                   1180:     }
                   1181: 
                   1182: 
                   1183:     function uncheckall() {
                   1184:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1185:             ele = document.forms.'.$form.'.elements[i];
                   1186:             if (ele.name == "'.$type.'") {
                   1187:             document.forms.'.$form.'.elements[i].checked=false;
                   1188:                                        }
                   1189:         }
                   1190:     }
                   1191: 
1.597     wenzelju 1192: '."\n");
1.249     albertel 1193:     return $chkallscript;
                   1194: }
                   1195: 
                   1196: sub check_buttons {
1.485     albertel 1197:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1198:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1199:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1200:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1201:     return $buttons;
                   1202: }
                   1203: 
1.44      ng       1204: #     Displays the submissions for one student or a group of students
1.34      ng       1205: sub processGroup {
1.41      ng       1206:     my ($request)  = shift;
                   1207:     my $ctr        = 0;
1.155     albertel 1208:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1209:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1210: 
1.396     banghart 1211:     foreach my $student (@stuchecked) {
                   1212: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1213: 	$env{'form.student'}        = $uname;
                   1214: 	$env{'form.userdom'}        = $udom;
                   1215: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1216: 	&submission($request,$ctr,$total);
                   1217: 	$ctr++;
                   1218:     }
                   1219:     return '';
1.35      ng       1220: }
1.34      ng       1221: 
1.44      ng       1222: #------------------------------------------------------------------------------------
                   1223: #
                   1224: #-------------------------- Next few routines handles grading by student, essentially
                   1225: #                           handles essay response type problem/part
                   1226: #
                   1227: #--- Javascript to handle the submission page functionality ---
                   1228: sub sub_page_js {
                   1229:     my $request = shift;
1.539     riegler  1230: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1231:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1232:     function updateRadio(formname,id,weight) {
1.125     ng       1233: 	var gradeBox = formname["GD_BOX"+id];
                   1234: 	var radioButton = formname["RADVAL"+id];
                   1235: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1236: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1237: 	gradeBox.value = pts;
                   1238: 	var resetbox = false;
                   1239: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1240: 	    alert("$alertmsg"+pts);
1.71      ng       1241: 	    for (var i=0; i<radioButton.length; i++) {
                   1242: 		if (radioButton[i].checked) {
                   1243: 		    gradeBox.value = i;
                   1244: 		    resetbox = true;
                   1245: 		}
                   1246: 	    }
                   1247: 	    if (!resetbox) {
                   1248: 		formtextbox.value = "";
                   1249: 	    }
                   1250: 	    return;
1.44      ng       1251: 	}
1.71      ng       1252: 
                   1253: 	if (pts > weight) {
                   1254: 	    var resp = confirm("You entered a value ("+pts+
                   1255: 			       ") greater than the weight for the part. Accept?");
                   1256: 	    if (resp == false) {
1.125     ng       1257: 		gradeBox.value = oldpts;
1.71      ng       1258: 		return;
                   1259: 	    }
1.44      ng       1260: 	}
1.13      albertel 1261: 
1.71      ng       1262: 	for (var i=0; i<radioButton.length; i++) {
                   1263: 	    radioButton[i].checked=false;
                   1264: 	    if (pts == i && pts != "") {
                   1265: 		radioButton[i].checked=true;
                   1266: 	    }
                   1267: 	}
                   1268: 	updateSelect(formname,id);
1.125     ng       1269: 	formname["stores"+id].value = "0";
1.41      ng       1270:     }
1.5       albertel 1271: 
1.72      ng       1272:     function writeBox(formname,id,pts) {
1.125     ng       1273: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1274: 	if (checkSolved(formname,id) == 'update') {
                   1275: 	    gradeBox.value = pts;
                   1276: 	} else {
1.125     ng       1277: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1278: 	    gradeBox.value = oldpts;
1.125     ng       1279: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1280: 	    for (var i=0; i<radioButton.length; i++) {
                   1281: 		radioButton[i].checked=false;
1.72      ng       1282: 		if (i == oldpts) {
1.71      ng       1283: 		    radioButton[i].checked=true;
                   1284: 		}
                   1285: 	    }
1.41      ng       1286: 	}
1.125     ng       1287: 	formname["stores"+id].value = "0";
1.71      ng       1288: 	updateSelect(formname,id);
                   1289: 	return;
1.41      ng       1290:     }
1.44      ng       1291: 
1.71      ng       1292:     function clearRadBox(formname,id) {
                   1293: 	if (checkSolved(formname,id) == 'noupdate') {
                   1294: 	    updateSelect(formname,id);
                   1295: 	    return;
                   1296: 	}
1.125     ng       1297: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1298: 	for (var i=0; i<gradeSelect.length; i++) {
                   1299: 	    if (gradeSelect[i].selected) {
                   1300: 		var selectx=i;
                   1301: 	    }
                   1302: 	}
1.125     ng       1303: 	var stores = formname["stores"+id];
1.71      ng       1304: 	if (selectx == stores.value) { return };
1.125     ng       1305: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1306: 	gradeBox.value = "";
1.125     ng       1307: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1308: 	for (var i=0; i<radioButton.length; i++) {
                   1309: 	    radioButton[i].checked=false;
                   1310: 	}
                   1311: 	stores.value = selectx;
                   1312:     }
1.5       albertel 1313: 
1.71      ng       1314:     function checkSolved(formname,id) {
1.125     ng       1315: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1316: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1317: 	    if (!reply) {return "noupdate";}
1.120     ng       1318: 	    formname.overRideScore.value = 'yes';
1.41      ng       1319: 	}
1.71      ng       1320: 	return "update";
1.13      albertel 1321:     }
1.71      ng       1322: 
                   1323:     function updateSelect(formname,id) {
1.125     ng       1324: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1325: 	return;
1.41      ng       1326:     }
1.33      ng       1327: 
1.121     ng       1328: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1329:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1330: 	formname.gradeOpt.value = val;
1.71      ng       1331: 	if (val == "Save & Next") {
                   1332: 	    for (i=0;i<=total;i++) {
                   1333: 		for (j=0;j<parttot;j++) {
1.125     ng       1334: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1335: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1336: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1337: 			if (points == "") {
1.125     ng       1338: 			    var name = formname["name"+i].value;
1.129     ng       1339: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1340: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1341: 					       ", part "+partid+". Continue?");
1.71      ng       1342: 			    if (resp == false) {
1.125     ng       1343: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1344: 				return false;
                   1345: 			    }
                   1346: 			}
                   1347: 		    }
                   1348: 		    
                   1349: 		}
                   1350: 	    }
                   1351: 	    
                   1352: 	}
1.121     ng       1353: 	if (val == "Grade Student") {
                   1354: 	    formname.showgrading.value = "yes";
                   1355: 	    if (formname.Status.value == "") {
                   1356: 		formname.Status.value = "Active";
                   1357: 	    }
                   1358: 	    formname.studentNo.value = total;
                   1359: 	}
1.120     ng       1360: 	formname.submit();
                   1361:     }
                   1362: 
1.71      ng       1363: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1364:     function checkSubmitPage(formname,total) {
                   1365: 	noscore = new Array(100);
                   1366: 	var ptr = 0;
                   1367: 	for (i=1;i<total;i++) {
1.125     ng       1368: 	    var partid = formname["q_"+i].value;
1.127     ng       1369: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1370: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1371: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1372: 		if (points == "" && status != "correct_by_student") {
                   1373: 		    noscore[ptr] = i;
                   1374: 		    ptr++;
                   1375: 		}
                   1376: 	    }
                   1377: 	}
                   1378: 	if (ptr != 0) {
                   1379: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1380: 	    var prolist = "";
                   1381: 	    if (ptr == 1) {
                   1382: 		prolist = noscore[0];
                   1383: 	    } else {
                   1384: 		var i = 0;
                   1385: 		while (i < ptr-1) {
                   1386: 		    prolist += noscore[i]+", ";
                   1387: 		    i++;
                   1388: 		}
                   1389: 		prolist += "and "+noscore[i];
                   1390: 	    }
                   1391: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1392: 	    if (resp == false) {
                   1393: 		return false;
                   1394: 	    }
                   1395: 	}
1.45      ng       1396: 
1.71      ng       1397: 	formname.submit();
                   1398:     }
                   1399: SUBJAVASCRIPT
                   1400: }
1.45      ng       1401: 
1.71      ng       1402: #--- javascript for essay type problem --
                   1403: sub sub_page_kw_js {
                   1404:     my $request = shift;
1.80      ng       1405:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1406:     &commonJSfunctions($request);
1.350     albertel 1407: 
1.597     wenzelju 1408:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1409:     function checkInput() {
                   1410:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1411:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1412:       var usrctr = document.msgcenter.usrctr.value;
                   1413:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1414:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1415: 
                   1416:       var msgchk = "";
                   1417:       if (document.msgcenter.subchk.checked) {
                   1418:          msgchk = "msgsub,";
                   1419:       }
                   1420:       var includemsg = 0;
                   1421:       for (var i=1; i<=nmsg; i++) {
                   1422:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1423:           var frmmsg = document.msgcenter["msg"+i];
                   1424:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1425:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1426:           showflg.value = "1";
                   1427:           var chkbox = document.msgcenter["msgn"+i];
                   1428:           if (chkbox.checked) {
                   1429:              msgchk += "savemsg"+i+",";
                   1430:              includemsg = 1;
                   1431:           }
                   1432:       }
                   1433:       if (document.msgcenter.newmsgchk.checked) {
                   1434:          msgchk += "newmsg"+usrctr;
                   1435:          includemsg = 1;
                   1436:       }
                   1437:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1438:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1439:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1440:       includemsg.value = msgchk;
                   1441: 
                   1442:       self.close()
                   1443: 
                   1444:     }
                   1445: INNERJS
                   1446: 
1.597     wenzelju 1447:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1448:     function updateChoice(flag) {
                   1449:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1450:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1451:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1452:       opener.document.SCORE.refresh.value = "on";
                   1453:       if (opener.document.SCORE.keywords.value!=""){
                   1454:          opener.document.SCORE.submit();
                   1455:       }
                   1456:       self.close()
                   1457:     }
                   1458: INNERJS
                   1459: 
                   1460:     my $start_page_msg_central = 
                   1461:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1462: 				       {'js_ready'  => 1,
                   1463: 					'only_body' => 1,
                   1464: 					'bgcolor'   =>'#FFFFFF',});
                   1465:     my $end_page_msg_central = 
                   1466: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1467: 
                   1468: 
                   1469:     my $start_page_highlight_central = 
                   1470:         &Apache::loncommon::start_page('Highlight Central',
                   1471: 				       $inner_js_highlight_central,
1.350     albertel 1472: 				       {'js_ready'  => 1,
                   1473: 					'only_body' => 1,
                   1474: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1475:     my $end_page_highlight_central = 
1.350     albertel 1476: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1477: 
1.219     www      1478:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1479:     $docopen=~s/^document\.//;
1.539     riegler  1480:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1481:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1482: 
1.44      ng       1483: //===================== Show list of keywords ====================
1.122     ng       1484:   function keywords(formname) {
                   1485:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1486:     if (nret==null) return;
1.122     ng       1487:     formname.keywords.value = nret;
1.44      ng       1488: 
1.122     ng       1489:     if (formname.keywords.value != "") {
1.128     ng       1490: 	formname.refresh.value = "on";
1.122     ng       1491: 	formname.submit();
1.44      ng       1492:     }
                   1493:     return;
                   1494:   }
                   1495: 
                   1496: //===================== Script to view submitted by ==================
                   1497:   function viewSubmitter(submitter) {
                   1498:     document.SCORE.refresh.value = "on";
                   1499:     document.SCORE.NCT.value = "1";
                   1500:     document.SCORE.unamedom0.value = submitter;
                   1501:     document.SCORE.submit();
                   1502:     return;
                   1503:   }
                   1504: 
                   1505: //===================== Script to add keyword(s) ==================
                   1506:   function getSel() {
                   1507:     if (document.getSelection) txt = document.getSelection();
                   1508:     else if (document.selection) txt = document.selection.createRange().text;
                   1509:     else return;
                   1510:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1511:     if (cleantxt=="") {
1.539     riegler  1512: 	alert("$alertmsg");
1.44      ng       1513: 	return;
                   1514:     }
                   1515:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1516:     if (nret==null) return;
1.127     ng       1517:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1518:     if (document.SCORE.keywords.value != "") {
1.127     ng       1519: 	document.SCORE.refresh.value = "on";
1.44      ng       1520: 	document.SCORE.submit();
                   1521:     }
                   1522:     return;
                   1523:   }
                   1524: 
                   1525: //====================== Script for composing message ==============
1.80      ng       1526:    // preload images
                   1527:    img1 = new Image();
                   1528:    img1.src = "$iconpath/mailbkgrd.gif";
                   1529:    img2 = new Image();
                   1530:    img2.src = "$iconpath/mailto.gif";
                   1531: 
1.44      ng       1532:   function msgCenter(msgform,usrctr,fullname) {
                   1533:     var Nmsg  = msgform.savemsgN.value;
                   1534:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1535:     var subject = msgform.msgsub.value;
1.127     ng       1536:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1537:     re = /msgsub/;
                   1538:     var shwsel = "";
                   1539:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1540:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1541:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1542:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1543: 	var testmsg = "savemsg"+i+",";
                   1544: 	re = new RegExp(testmsg,"g");
1.44      ng       1545: 	shwsel = "";
                   1546: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1547: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1548: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1549: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1550: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1551:     }
1.125     ng       1552:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1553:     shwsel = "";
                   1554:     re = /newmsg/;
                   1555:     if (re.test(msgchk)) { shwsel = "checked" }
                   1556:     newMsg(newmsg,shwsel);
                   1557:     msgTail(); 
                   1558:     return;
                   1559:   }
                   1560: 
1.123     ng       1561:   function checkEntities(strx) {
                   1562:     if (strx.length == 0) return strx;
                   1563:     var orgStr = ["&", "<", ">", '"']; 
                   1564:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1565:     var counter = 0;
                   1566:     while (counter < 4) {
                   1567: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1568: 	counter++;
                   1569:     }
                   1570:     return strx;
                   1571:   }
                   1572: 
                   1573:   function strReplace(strx, orgStr, newStr) {
                   1574:     return strx.split(orgStr).join(newStr);
                   1575:   }
                   1576: 
1.44      ng       1577:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1578:     var height = 70*Nmsg+250;
1.44      ng       1579:     var scrollbar = "no";
                   1580:     if (height > 600) {
                   1581: 	height = 600;
                   1582: 	scrollbar = "yes";
                   1583:     }
1.118     ng       1584:     var xpos = (screen.width-600)/2;
                   1585:     xpos = (xpos < 0) ? '0' : xpos;
                   1586:     var ypos = (screen.height-height)/2-30;
                   1587:     ypos = (ypos < 0) ? '0' : ypos;
                   1588: 
1.206     albertel 1589:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1590:     pWin.focus();
                   1591:     pDoc = pWin.document;
1.219     www      1592:     pDoc.$docopen;
1.351     albertel 1593:     pDoc.write('$start_page_msg_central');
1.76      ng       1594: 
                   1595:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1596:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1597:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1598: 
1.564     bisitz   1599:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1600:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1601:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1602: }
                   1603:     function displaySubject(msg,shwsel) {
1.76      ng       1604:     pDoc = pWin.document;
                   1605:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1606:     pDoc.write("<td>Subject<\\/td>");
                   1607:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1608:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1609: }
                   1610: 
1.72      ng       1611:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1612:     pDoc = pWin.document;
                   1613:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1614:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1615:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1616:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1617: }
                   1618: 
                   1619:   function newMsg(newmsg,shwsel) {
1.76      ng       1620:     pDoc = pWin.document;
                   1621:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1622:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1623:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1624:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1625: }
                   1626: 
                   1627:   function msgTail() {
1.76      ng       1628:     pDoc = pWin.document;
1.465     albertel 1629:     pDoc.write("<\\/table>");
                   1630:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1631:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1632:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1633:     pDoc.write("<\\/form>");
1.351     albertel 1634:     pDoc.write('$end_page_msg_central');
1.128     ng       1635:     pDoc.close();
1.44      ng       1636: }
                   1637: 
                   1638: //====================== Script for keyword highlight options ==============
                   1639:   function kwhighlight() {
                   1640:     var kwclr    = document.SCORE.kwclr.value;
                   1641:     var kwsize   = document.SCORE.kwsize.value;
                   1642:     var kwstyle  = document.SCORE.kwstyle.value;
                   1643:     var redsel = "";
                   1644:     var grnsel = "";
                   1645:     var blusel = "";
                   1646:     if (kwclr=="red")   {var redsel="checked"};
                   1647:     if (kwclr=="green") {var grnsel="checked"};
                   1648:     if (kwclr=="blue")  {var blusel="checked"};
                   1649:     var sznsel = "";
                   1650:     var sz1sel = "";
                   1651:     var sz2sel = "";
                   1652:     if (kwsize=="0")  {var sznsel="checked"};
                   1653:     if (kwsize=="+1") {var sz1sel="checked"};
                   1654:     if (kwsize=="+2") {var sz2sel="checked"};
                   1655:     var synsel = "";
                   1656:     var syisel = "";
                   1657:     var sybsel = "";
                   1658:     if (kwstyle=="")    {var synsel="checked"};
                   1659:     if (kwstyle=="<i>") {var syisel="checked"};
                   1660:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1661:     highlightCentral();
                   1662:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1663:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1664:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1665:     highlightend();
                   1666:     return;
                   1667:   }
                   1668: 
                   1669:   function highlightCentral() {
1.76      ng       1670: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1671:     var xpos = (screen.width-400)/2;
                   1672:     xpos = (xpos < 0) ? '0' : xpos;
                   1673:     var ypos = (screen.height-330)/2-30;
                   1674:     ypos = (ypos < 0) ? '0' : ypos;
                   1675: 
1.206     albertel 1676:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1677:     hwdWin.focus();
                   1678:     var hDoc = hwdWin.document;
1.219     www      1679:     hDoc.$docopen;
1.351     albertel 1680:     hDoc.write('$start_page_highlight_central');
1.76      ng       1681:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1682:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1683: 
1.564     bisitz   1684:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1685:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1686:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1687:   }
                   1688: 
                   1689:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1690:     var hDoc = hwdWin.document;
                   1691:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1692:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1693:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1694:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1695:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1696:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1697:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1698:     hDoc.write("<\\/tr>");
1.44      ng       1699:   }
                   1700: 
                   1701:   function highlightend() { 
1.76      ng       1702:     var hDoc = hwdWin.document;
1.465     albertel 1703:     hDoc.write("<\\/table>");
                   1704:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1705:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1706:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1707:     hDoc.write("<\\/form>");
1.351     albertel 1708:     hDoc.write('$end_page_highlight_central');
1.128     ng       1709:     hDoc.close();
1.44      ng       1710:   }
                   1711: 
                   1712: SUBJAVASCRIPT
                   1713: }
                   1714: 
1.349     albertel 1715: sub get_increment {
1.348     bowersj2 1716:     my $increment = $env{'form.increment'};
                   1717:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1718:         $increment != .1) {
                   1719:         $increment = 1;
                   1720:     }
                   1721:     return $increment;
                   1722: }
                   1723: 
1.585     bisitz   1724: sub gradeBox_start {
                   1725:     return (
                   1726:         &Apache::loncommon::start_data_table()
                   1727:        .&Apache::loncommon::start_data_table_header_row()
                   1728:        .'<th>'.&mt('Part').'</th>'
                   1729:        .'<th>'.&mt('Points').'</th>'
                   1730:        .'<th>&nbsp;</th>'
                   1731:        .'<th>'.&mt('Assign Grade').'</th>'
                   1732:        .'<th>'.&mt('Weight').'</th>'
                   1733:        .'<th>'.&mt('Grade Status').'</th>'
                   1734:        .&Apache::loncommon::end_data_table_header_row()
                   1735:     );
                   1736: }
                   1737: 
                   1738: sub gradeBox_end {
                   1739:     return (
                   1740:         &Apache::loncommon::end_data_table()
                   1741:     );
                   1742: }
1.71      ng       1743: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1744: sub gradeBox {
1.322     albertel 1745:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1746:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1747: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1748:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1749:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1750:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1751:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1752:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1753: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1754:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1755:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1756:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1757: 				       [$partid]);
                   1758:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1759:     if ($last_resets{$partid}) {
                   1760:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1761:     }
1.585     bisitz   1762:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1763:     my $ctr = 0;
1.348     bowersj2 1764:     my $thisweight = 0;
1.349     albertel 1765:     my $increment = &get_increment();
1.485     albertel 1766: 
                   1767:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1768:     while ($thisweight<=$wgt) {
1.532     bisitz   1769: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1770:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1771: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1772: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1773: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1774:         $thisweight += $increment;
1.71      ng       1775: 	$ctr++;
                   1776:     }
1.485     albertel 1777:     $radio.='</tr></table>';
                   1778: 
                   1779:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1780: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1781: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1782: 	$wgt.')" /></td>'."\n";
1.485     albertel 1783:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1784: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1785: 	' </td>'."\n";
                   1786:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1787: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1788:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1789: 	$line.='<option></option>'.
                   1790: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1791:     } else {
1.485     albertel 1792: 	$line.='<option selected="selected"></option>'.
                   1793: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1794:     }
1.485     albertel 1795:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1796: 
                   1797: 
1.540     riegler  1798: 	#&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
1.485     albertel 1799:     $result .= 
1.585     bisitz   1800: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1801:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1802:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1803: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1804: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1805: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1806:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1807:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1808:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1809:         $aggtries.'" />'."\n";
1.582     raeburn  1810:     my $res_error;
                   1811:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1812:     if ($res_error) {
                   1813:         return &navmap_errormsg();
                   1814:     }
1.318     banghart 1815:     return $result;
                   1816: }
1.322     albertel 1817: 
                   1818: sub handback_box {
1.582     raeburn  1819:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1820:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1821:     my (@respids);
1.375     albertel 1822:      my @part_response_id = &flatten_responseType($responseType);
                   1823:     foreach my $part_response_id (@part_response_id) {
                   1824:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1825:         if ($part eq $partid) {
1.375     albertel 1826:             push(@respids,$resp);
1.323     banghart 1827:         }
                   1828:     }
1.318     banghart 1829:     my $result;
1.323     banghart 1830:     foreach my $respid (@respids) {
1.322     albertel 1831: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1832: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1833: 	next if (!@$files);
                   1834: 	my $file_counter = 1;
1.313     banghart 1835: 	foreach my $file (@$files) {
1.368     banghart 1836: 	    if ($file =~ /\/portfolio\//) {
                   1837:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1838:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1839:     	        $file_disp = "$name.$ext";
                   1840:     	        $file = $file_path.$file_disp;
                   1841:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1842:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1843:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1844:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1845:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1846:     	        $file_counter++;
                   1847: 	    }
1.322     albertel 1848: 	}
1.313     banghart 1849:     }
1.318     banghart 1850:     return $result;    
1.71      ng       1851: }
1.44      ng       1852: 
1.58      albertel 1853: sub show_problem {
1.382     albertel 1854:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1855:     my $rendered;
1.382     albertel 1856:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1857:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1858:     if ($mode eq 'both' or $mode eq 'text') {
                   1859: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1860: 						       $env{'request.course.id'},
                   1861: 						       undef,\%form);
1.144     albertel 1862:     }
1.58      albertel 1863:     if ($removeform) {
                   1864: 	$rendered=~s|<form(.*?)>||g;
                   1865: 	$rendered=~s|</form>||g;
1.374     albertel 1866: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1867:     }
1.144     albertel 1868:     my $companswer;
                   1869:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1870: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1871: 	$companswer=
                   1872: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1873: 						    $env{'request.course.id'},
                   1874: 						    %form);
1.144     albertel 1875:     }
1.58      albertel 1876:     if ($removeform) {
                   1877: 	$companswer=~s|<form(.*?)>||g;
                   1878: 	$companswer=~s|</form>||g;
1.144     albertel 1879: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1880:     }
1.468     albertel 1881:     $rendered=
1.588     bisitz   1882:         '<div class="LC_Box">'
                   1883:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1884:        .$rendered
                   1885:        .'</div>';
1.468     albertel 1886:     $companswer=
1.588     bisitz   1887:         '<div class="LC_Box">'
                   1888:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1889:        .$companswer
                   1890:        .'</div>';
1.468     albertel 1891:     my $result;
1.144     albertel 1892:     if ($mode eq 'both') {
1.588     bisitz   1893:         $result=$rendered.$companswer;
1.144     albertel 1894:     } elsif ($mode eq 'text') {
1.588     bisitz   1895:         $result=$rendered;
1.144     albertel 1896:     } elsif ($mode eq 'answer') {
1.588     bisitz   1897:         $result=$companswer;
1.144     albertel 1898:     }
1.71      ng       1899:     return $result;
1.58      albertel 1900: }
1.397     albertel 1901: 
1.396     banghart 1902: sub files_exist {
                   1903:     my ($r, $symb) = @_;
                   1904:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1905: 
1.396     banghart 1906:     foreach my $student (@students) {
                   1907:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1908:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1909: 					      $udom,$uname);
1.396     banghart 1910:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1911:         foreach my $submission (@$string) {
                   1912:             my ($partid,$respid) =
                   1913: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1914:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1915: 					   \%record);
                   1916:             return 1 if (@$files);
1.396     banghart 1917:         }
                   1918:     }
1.397     albertel 1919:     return 0;
1.396     banghart 1920: }
1.397     albertel 1921: 
1.394     banghart 1922: sub download_all_link {
                   1923:     my ($r,$symb) = @_;
1.395     albertel 1924:     my $all_students = 
                   1925: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1926: 
                   1927:     my $parts =
                   1928: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1929: 
1.394     banghart 1930:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1931:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1932:                              'cgi.'.$identifier.'.symb' => $symb,
                   1933:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1934:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1935: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1936:     return
                   1937: }
1.395     albertel 1938: 
1.432     banghart 1939: sub build_section_inputs {
                   1940:     my $section_inputs;
                   1941:     if ($env{'form.section'} eq '') {
                   1942:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1943:     } else {
                   1944:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1945:         foreach my $section (@sections) {
1.432     banghart 1946:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1947:         }
                   1948:     }
                   1949:     return $section_inputs;
                   1950: }
                   1951: 
1.44      ng       1952: # --------------------------- show submissions of a student, option to grade 
                   1953: sub submission {
                   1954:     my ($request,$counter,$total) = @_;
1.257     albertel 1955:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1956:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1957:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1958:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1959:     my $symb = &get_symb($request); 
                   1960:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1961: 
                   1962:     if (!&canview($usec)) {
1.398     albertel 1963: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1964: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1965: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1966: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1967: 	return;
                   1968:     }
                   1969: 
1.257     albertel 1970:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1971:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1972:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1973:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1974:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1975: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1976: 	'/check.gif" height="16" border="0" />';
1.41      ng       1977: 
1.426     albertel 1978:     my %old_essays;
1.41      ng       1979:     # header info
                   1980:     if ($counter == 0) {
                   1981: 	&sub_page_js($request);
1.257     albertel 1982: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1983: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1984: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1985: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1986: 	    &download_all_link($request, $symb);
                   1987: 	}
1.485     albertel 1988: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1989: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1990: 
1.44      ng       1991: 	# option to display problem, only once else it cause problems 
                   1992:         # with the form later since the problem has a form.
1.257     albertel 1993: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1994: 	    my $mode;
1.257     albertel 1995: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1996: 		$mode='both';
1.257     albertel 1997: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1998: 		$mode='text';
1.257     albertel 1999: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2000: 		$mode='answer';
                   2001: 	    }
1.329     albertel 2002: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2003: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2004: 	}
1.441     www      2005: 
1.44      ng       2006: 	# kwclr is the only variable that is guaranteed to be non blank 
                   2007:         # if this subroutine has been called once.
1.41      ng       2008: 	my %keyhash = ();
1.257     albertel 2009: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2010: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2011: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2012: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2013: 
1.257     albertel 2014: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2015: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2016: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2017: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2018: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2019: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2020: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2021: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2022: 	}
1.257     albertel 2023: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2024: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2025: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2026: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2027: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2028: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2029: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2030: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2031: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2032: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2033: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2034: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2035: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2036: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2037: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2038: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2039: 			&build_section_inputs().
1.326     albertel 2040: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2041: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2042: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2043: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2044: 	if ($env{'form.handgrade'} eq 'yes') {
                   2045: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2046: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2047: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2048: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2049: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2050: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2051: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2052: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2053: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2054: 	    }
1.123     ng       2055: 	}
1.41      ng       2056: 	
                   2057: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2058: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2059: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2060: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2061: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2062: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2063: 		'" />'."\n".
                   2064: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2065: 	    $cts++;
                   2066: 	}
                   2067: 	$request->print($prnmsg);
1.32      ng       2068: 
1.257     albertel 2069: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2070: #
                   2071: # Print out the keyword options line
                   2072: #
1.41      ng       2073: 	    $request->print(<<KEYWORDS);
1.38      ng       2074: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2075: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2076: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2077:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2078: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2079: KEYWORDS
1.88      www      2080: #
                   2081: # Load the other essays for similarity check
                   2082: #
1.324     albertel 2083:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2084: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2085: 	    $apath=&escape($apath);
1.88      www      2086: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2087: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2088:         }
                   2089:     }
1.44      ng       2090: 
1.441     www      2091: # This is where output for one specific student would start
1.592     bisitz   2092:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2093:     $request->print(
                   2094:         "\n\n"
                   2095:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2096:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2097:        ."\n"
                   2098:     );
1.441     www      2099: 
1.592     bisitz   2100:     # Show additional functions if allowed
                   2101:     if ($perm{'vgr'}) {
                   2102:         $request->print(
                   2103:             &Apache::loncommon::track_student_link(
                   2104:                 &mt('View recent activity'),
                   2105:                 $uname,$udom,'check')
                   2106:            .' '
                   2107:         );
                   2108:     }
                   2109:     if ($perm{'opa'}) {
                   2110:         $request->print(
                   2111:             &Apache::loncommon::pprmlink(
                   2112:                 &mt('Set/Change parameters'),
                   2113:                 $uname,$udom,$symb,'check'));
                   2114:     }
                   2115: 
                   2116:     # Show Problem
1.257     albertel 2117:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2118: 	my $mode;
1.257     albertel 2119: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2120: 	    $mode='both';
1.257     albertel 2121: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2122: 	    $mode='text';
1.257     albertel 2123: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2124: 	    $mode='answer';
                   2125: 	}
1.329     albertel 2126: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2127: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2128:     }
1.144     albertel 2129: 
1.257     albertel 2130:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2131:     my $res_error;
                   2132:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2133:     if ($res_error) {
                   2134:         $request->print(&navmap_errormsg());
                   2135:         return;
                   2136:     }
1.41      ng       2137: 
1.44      ng       2138:     # Display student info
1.41      ng       2139:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2140: 
                   2141:     my $result='<div class="LC_Box">'
                   2142:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2143:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2144:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2145:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2146:         $result.='<p class="LC_info">'
                   2147:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2148:                 ."</p>\n";
1.469     albertel 2149:     }
                   2150: 
1.118     ng       2151:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2152:     my $fullname;
                   2153:     my $col_fullnames = [];
1.257     albertel 2154:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2155: 	(my $sub_result,$fullname,$col_fullnames)=
                   2156: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2157: 				 $counter);
                   2158: 	$result.=$sub_result;
1.41      ng       2159:     }
1.44      ng       2160:     $request->print($result."\n");
1.588     bisitz   2161: 
1.44      ng       2162:     # print student answer/submission
1.588     bisitz   2163:     # Options are (1) Handgraded submission only
1.44      ng       2164:     #             (2) Last submission, includes submission that is not handgraded 
                   2165:     #                  (for multi-response type part)
                   2166:     #             (3) Last submission plus the parts info
                   2167:     #             (4) The whole record for this student
1.257     albertel 2168:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2169: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2170: 	
                   2171: 	my $lastsubonly;
                   2172: 
1.588     bisitz   2173:         if ($$timestamp eq '') {
                   2174:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2175:         } else {
1.592     bisitz   2176:             $lastsubonly =
                   2177:                 '<div class="LC_grade_submissions_body">'
                   2178:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2179: 
1.151     albertel 2180: 	    my %seenparts;
1.375     albertel 2181: 	    my @part_response_id = &flatten_responseType($responseType);
                   2182: 	    foreach my $part (@part_response_id) {
1.393     albertel 2183: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2184: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2185: 
1.375     albertel 2186: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2187: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2188: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2189: 		    if (exists($seenparts{$partid})) { next; }
                   2190: 		    $seenparts{$partid}=1;
1.207     albertel 2191: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2192: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2193: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2194: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2195: 			'\');" target="_self">'.
1.257     albertel 2196: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2197: 		    $request->print($submitby);
                   2198: 		    next;
                   2199: 		}
                   2200: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2201: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2202:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2203:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2204:                         ' <span class="LC_internal_info">'.
1.597     wenzelju 2205:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2206:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2207: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2208: 		    next;
                   2209: 		}
1.468     albertel 2210: 		foreach my $submission (@$string) {
                   2211: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2212: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2213: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2214: 		    # Similarity check
                   2215: 		    my $similar='';
1.257     albertel 2216: 		    if($env{'form.checkPlag'}){
1.151     albertel 2217: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2218: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2219: 			if ($osim) {
                   2220: 			    $osim=int($osim*100.0);
1.426     albertel 2221: 			    my %old_course_desc = 
                   2222: 				&Apache::lonnet::coursedescription($ocrsid,
                   2223: 								   {'one_time' => 1});
                   2224: 
1.596     raeburn  2225:                             if ($hide) {
                   2226:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2227:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2228:                             } else {
                   2229: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2230: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2231: 				        $osim,
                   2232: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2233: 				        $old_course_desc{'description'},
                   2234: 				        $old_course_desc{'num'},
                   2235: 				        $old_course_desc{'domain'}).
                   2236: 				    '</span></h3><blockquote><i>'.
                   2237: 				    &keywords_highlight($oessay).
                   2238: 				    '</i></blockquote><hr />';
                   2239:                             }
1.151     albertel 2240: 			}
1.150     albertel 2241: 		    }
1.151     albertel 2242: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2243: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2244: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2245: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2246: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2247:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2248:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2249:                             ' <span class="LC_internal_info">'.
                   2250:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597     wenzelju 2251:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2252: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2253: 			if (@$files) {
1.596     raeburn  2254:                             if ($hide) {
                   2255:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2256:                             } else {
                   2257:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2258:                                 foreach my $file (@$files) {
                   2259:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2260:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2261:                                 }
                   2262:                             }
1.236     albertel 2263: 			    $lastsubonly.='<br />';
1.41      ng       2264: 			}
1.596     raeburn  2265:                         if ($hide) {
                   2266:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2267:                         } else {
                   2268: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2269: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2270: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2271:                         }
1.151     albertel 2272: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2273: 			$lastsubonly.='</div>';
1.41      ng       2274: 		    }
                   2275: 		}
                   2276: 	    }
1.588     bisitz   2277: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2278: 	}
                   2279: 	$request->print($lastsubonly);
1.468     albertel 2280:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.598   ! www      2281: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
        !          2282:     my ($parts,$handgrade,$responseType) = &response_type($symb);
        !          2283: 
1.148     albertel 2284: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2285:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2286: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2287: 								 $env{'request.course.id'},
1.44      ng       2288: 								 $last,'.submission',
                   2289: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2290:     }
1.120     ng       2291: 
1.121     ng       2292:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2293: 	.$udom.'" />'."\n");
1.44      ng       2294:     # return if view submission with no grading option
1.257     albertel 2295:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2296: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2297: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2298: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2299: 	$toGrade.='</div>'."\n";
1.257     albertel 2300: 	if (($env{'form.command'} eq 'submission') || 
                   2301: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2302: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2303: 	}
1.180     albertel 2304: 	$request->print($toGrade);
1.41      ng       2305: 	return;
1.180     albertel 2306:     } else {
1.468     albertel 2307: 	$request->print('</div>'."\n");
1.41      ng       2308:     }
1.33      ng       2309: 
1.121     ng       2310:     # essay grading message center
1.257     albertel 2311:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2312: 	my $result='<div class="LC_grade_message_center">';
                   2313:     
                   2314: 	$result.='<div class="LC_grade_message_center_header">'.
                   2315: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2316: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2317: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2318: 	if (scalar(@$col_fullnames) > 0) {
                   2319: 	    my $lastone = pop(@$col_fullnames);
                   2320: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2321: 	}
                   2322: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2323: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2324: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2325: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2326: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2327: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2328: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2329: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2330: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2331: 	    '<br />&nbsp;('.
1.468     albertel 2332: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2333: 	$result.='</div></div>';
1.121     ng       2334: 	$request->print($result);
1.118     ng       2335:     }
1.41      ng       2336: 
                   2337:     my %seen = ();
                   2338:     my @partlist;
1.129     ng       2339:     my @gradePartRespid;
1.375     albertel 2340:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2341:     $request->print(
1.588     bisitz   2342:         '<div class="LC_Box">'
                   2343:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2344:     );
1.592     bisitz   2345:     $request->print(&gradeBox_start());
1.375     albertel 2346:     foreach my $part_response_id (@part_response_id) {
                   2347:     	my ($partid,$respid) = @{ $part_response_id };
                   2348: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2349: 	next if ($seen{$partid} > 0);
1.41      ng       2350: 	$seen{$partid}++;
1.393     albertel 2351: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2352: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2353: 	push(@partlist,$partid);
                   2354: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2355: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2356:     }
1.585     bisitz   2357:     $request->print(&gradeBox_end()); # </div>
                   2358:     $request->print('</div>');
1.468     albertel 2359: 
                   2360:     $request->print('<div class="LC_grade_info_links">');
                   2361:     $request->print('</div>');
                   2362: 
1.45      ng       2363:     $result='<input type="hidden" name="partlist'.$counter.
                   2364: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2365:     $result.='<input type="hidden" name="gradePartRespid'.
                   2366: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2367:     my $ctr = 0;
                   2368:     while ($ctr < scalar(@partlist)) {
                   2369: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2370: 	    $partlist[$ctr].'" />'."\n";
                   2371: 	$ctr++;
                   2372:     }
1.468     albertel 2373:     $request->print($result.''."\n");
1.41      ng       2374: 
1.441     www      2375: # Done with printing info for one student
                   2376: 
1.468     albertel 2377:     $request->print('</div>');#LC_grade_show_user
1.441     www      2378: 
                   2379: 
1.41      ng       2380:     # print end of form
                   2381:     if ($counter == $total) {
1.592     bisitz   2382:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2383: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2384: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2385: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2386: 	my $ntstu ='<select name="NTSTU">'.
                   2387: 	    '<option>1</option><option>2</option>'.
                   2388: 	    '<option>3</option><option>5</option>'.
                   2389: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2390: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2391: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2392:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2393: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2394: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2395: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2396: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2397:         $endform.='<span class="LC_warning">'.
                   2398:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2399:                   '</span>'."\n" ;
1.349     albertel 2400:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2401:             "' name='increment' />";
1.485     albertel 2402: 	$endform.='</td></tr></table></form>';
1.324     albertel 2403: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2404: 	$request->print($endform);
                   2405:     }
                   2406:     return '';
1.38      ng       2407: }
                   2408: 
1.464     albertel 2409: sub check_collaborators {
                   2410:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2411:     my ($result,@col_fullnames);
                   2412:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2413:     foreach my $part (keys(%$handgrade)) {
                   2414: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2415: 					'.maxcollaborators',
                   2416: 					$symb,$udom,$uname);
                   2417: 	next if ($ncol <= 0);
                   2418: 	$part =~ s/\_/\./g;
                   2419: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2420: 	my (@good_collaborators, @bad_collaborators);
                   2421: 	foreach my $possible_collaborator
                   2422: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2423: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2424: 	    next if ($possible_collaborator eq '');
                   2425: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2426: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2427: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2428: 	    # Doing this grep allows 'fuzzy' specification
                   2429: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2430: 			       keys(%$classlist));
                   2431: 	    if (! scalar(@matches)) {
                   2432: 		push(@bad_collaborators, $possible_collaborator);
                   2433: 	    } else {
                   2434: 		push(@good_collaborators, @matches);
                   2435: 	    }
                   2436: 	}
                   2437: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2438: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2439: 	    foreach my $name (@good_collaborators) {
                   2440: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2441: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2442: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2443: 	    }
                   2444: 	    $result.='<br />'."\n";
1.466     albertel 2445: 	    my ($part)=split(/\./,$part);
1.464     albertel 2446: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2447: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2448: 		"\n";
                   2449: 	}
                   2450: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2451: 	    $result.='<div class="LC_warning">';
1.464     albertel 2452: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2453: 	    $result .= '</div>';
                   2454: 	}         
                   2455: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2456: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2457: 	    $result .= &mt('This student has submitted too many '.
                   2458: 		'collaborators.  Maximum is [_1].',$ncol);
                   2459: 	    $result .= '</div>';
                   2460: 	}
                   2461:     }
                   2462:     return ($result,$fullname,\@col_fullnames);
                   2463: }
                   2464: 
1.44      ng       2465: #--- Retrieve the last submission for all the parts
1.38      ng       2466: sub get_last_submission {
1.119     ng       2467:     my ($returnhash)=@_;
1.596     raeburn  2468:     my (@string,$timestamp,%lasthidden);
1.119     ng       2469:     if ($$returnhash{'version'}) {
1.46      ng       2470: 	my %lasthash=();
                   2471: 	my ($version);
1.119     ng       2472: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2473: 	    foreach my $key (sort(split(/\:/,
                   2474: 					$$returnhash{$version.':keys'}))) {
                   2475: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2476: 		$timestamp = 
1.545     raeburn  2477: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2478: 	    }
                   2479: 	}
1.596     raeburn  2480:         my %typeparts;
                   2481:         my $showsurv = 
                   2482:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2483:         foreach my $key (sort(keys(%lasthash))) {
                   2484:             if ($key =~ /\.type$/) {
                   2485:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2486:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2487:                     my ($ign,@parts) = split(/\./,$key);
                   2488:                     pop(@parts);
                   2489:                     unless ($showsurv) {
                   2490:                         my $id = join(',',@parts);
                   2491:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2492:                     }
                   2493:                     delete($lasthash{$key});
                   2494:                 }
                   2495:             }
                   2496:         }
                   2497:         my @hidden = keys(%typeparts);
1.397     albertel 2498: 	foreach my $key (keys(%lasthash)) {
                   2499: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2500:             my $hide;
                   2501:             if (@hidden) {
                   2502:                 foreach my $id (@hidden) {
                   2503:                     if ($key =~ /^\Q$id\E/) {
                   2504:                         $hide = 1;
                   2505:                         last;
                   2506:                     }
                   2507:                 }
                   2508:             }
1.397     albertel 2509: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2510: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2511: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2512: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2513: 	}
                   2514:     }
1.397     albertel 2515:     if (!@string) {
                   2516: 	$string[0] =
1.539     riegler  2517: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2518:     }
                   2519:     return (\@string,\$timestamp);
1.38      ng       2520: }
1.35      ng       2521: 
1.44      ng       2522: #--- High light keywords, with style choosen by user.
1.38      ng       2523: sub keywords_highlight {
1.44      ng       2524:     my $string    = shift;
1.257     albertel 2525:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2526:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2527:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2528:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2529:     foreach my $keyword (@keylist) {
                   2530: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2531:     }
                   2532:     return $string;
1.38      ng       2533: }
1.36      ng       2534: 
1.44      ng       2535: #--- Called from submission routine
1.38      ng       2536: sub processHandGrade {
1.41      ng       2537:     my ($request) = shift;
1.324     albertel 2538:     my $symb   = &get_symb($request);
                   2539:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2540:     my $button = $env{'form.gradeOpt'};
                   2541:     my $ngrade = $env{'form.NCT'};
                   2542:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2543:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2544:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2545: 
1.44      ng       2546:     if ($button eq 'Save & Next') {
                   2547: 	my $ctr = 0;
                   2548: 	while ($ctr < $ngrade) {
1.257     albertel 2549: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2550: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2551: 	    if ($errorflag eq 'no_score') {
                   2552: 		$ctr++;
                   2553: 		next;
                   2554: 	    }
1.104     albertel 2555: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2556: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2557: 		$ctr++;
                   2558: 		next;
                   2559: 	    }
1.257     albertel 2560: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2561: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2562: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2563:             my ($feedurl,$showsymb) =
                   2564: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2565: 	    my $messagetail;
1.62      albertel 2566: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2567: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2568: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2569: 		$subject.=' ['.$restitle.']';
1.44      ng       2570: 		my (@msgnum) = split(/,/,$includemsg);
                   2571: 		foreach (@msgnum) {
1.257     albertel 2572: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2573: 		}
1.80      ng       2574: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2575: 		if ($env{'form.withgrades'.$ctr}) {
                   2576: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2577: 		    $messagetail = " for <a href=\"".
1.418     albertel 2578: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2579: 		}
                   2580: 		$msgstatus = 
                   2581:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2582: 						     $message.$messagetail,
1.418     albertel 2583:                                                      undef,$feedurl,undef,
1.386     raeburn  2584:                                                      undef,undef,$showsymb,
                   2585:                                                      $restitle);
1.574     bisitz   2586: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2587: 				$msgstatus);
1.44      ng       2588: 	    }
1.257     albertel 2589: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2590: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2591: 		foreach my $collabstr (@collabstrs) {
                   2592: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2593: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2594: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2595: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2596: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2597: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2598: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2599: 			    next;
1.418     albertel 2600: 			} elsif ($message ne '') {
                   2601: 			    my ($baseurl,$showsymb) = 
                   2602: 				&get_feedurl_and_symb($symb,$collaborator,
                   2603: 						      $udom);
                   2604: 			    if ($env{'form.withgrades'.$ctr}) {
                   2605: 				$messagetail = " for <a href=\"".
1.386     raeburn  2606:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2607: 			    }
1.418     albertel 2608: 			    $msgstatus = 
                   2609: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2610: 			}
1.44      ng       2611: 		    }
                   2612: 		}
                   2613: 	    }
                   2614: 	    $ctr++;
                   2615: 	}
                   2616:     }
                   2617: 
1.257     albertel 2618:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2619: 	# Keywords sorted in alphabatical order
1.257     albertel 2620: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2621: 	my %keyhash = ();
1.257     albertel 2622: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2623: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2624: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2625: 	$env{'form.keywords'} = join(' ',@keywords);
                   2626: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2627: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2628: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2629: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2630: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2631: 
                   2632: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2633: 	# New messages are saved in env for the next student.
1.119     ng       2634: 	# All messages are saved in nohist_handgrade.db
                   2635: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2636: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2637: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2638: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2639: 		$idx++;
                   2640: 	    }
                   2641: 	    $ctr++;
1.41      ng       2642: 	}
1.119     ng       2643: 	$ctr = 0;
                   2644: 	while ($ctr < $ngrade) {
1.257     albertel 2645: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2646: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2647: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2648: 		$idx++;
                   2649: 	    }
                   2650: 	    $ctr++;
1.41      ng       2651: 	}
1.257     albertel 2652: 	$env{'form.savemsgN'} = --$idx;
                   2653: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2654: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2655: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2656:     }
1.44      ng       2657:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2658:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2659:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2660: 	my ($ctr,$total) = (0,0);
                   2661: 	while ($ctr < $ngrade) {
1.257     albertel 2662: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2663: 	    $ctr++;
                   2664: 	}
1.257     albertel 2665: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2666: 	$ctr = 0;
                   2667: 	while ($ctr < $total) {
1.257     albertel 2668: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2669: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2670: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2671: 	    &submission($request,$ctr,$total-1);
1.41      ng       2672: 	    $ctr++;
                   2673: 	}
                   2674: 	return '';
                   2675:     }
1.36      ng       2676: 
1.121     ng       2677: # Go directly to grade student - from submission or link from chart page
1.120     ng       2678:     if ($button eq 'Grade Student') {
1.598   ! www      2679: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2680: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2681: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2682: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2683: 	&submission($request,0,0);
                   2684: 	return '';
                   2685:     }
                   2686: 
1.44      ng       2687:     # Get the next/previous one or group of students
1.257     albertel 2688:     my $firststu = $env{'form.unamedom0'};
                   2689:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2690:     my $ctr = 2;
1.41      ng       2691:     while ($laststu eq '') {
1.257     albertel 2692: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2693: 	$ctr++;
                   2694: 	$laststu = $firststu if ($ctr > $ngrade);
                   2695:     }
1.44      ng       2696: 
1.41      ng       2697:     my (@parsedlist,@nextlist);
                   2698:     my ($nextflg) = 0;
1.524     raeburn  2699:     foreach my $item (sort 
1.294     albertel 2700: 	     {
                   2701: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2702: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2703: 		 }
                   2704: 		 return $a cmp $b;
                   2705: 	     } (keys(%$fullname))) {
1.41      ng       2706: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2707: 	    push(@parsedlist,$item);
1.41      ng       2708: 	}
1.524     raeburn  2709: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2710: 	if ($button eq 'Previous') {
1.524     raeburn  2711: 	    last if ($item eq $firststu);
                   2712: 	    push(@parsedlist,$item);
1.41      ng       2713: 	}
                   2714:     }
                   2715:     $ctr = 0;
                   2716:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2717:     my $res_error;
                   2718:     my ($partlist) = &response_type($symb,\$res_error);
                   2719:     if ($res_error) {
                   2720:         $request->print(&navmap_errormsg());
                   2721:         return;
                   2722:     }
1.41      ng       2723:     foreach my $student (@parsedlist) {
1.257     albertel 2724: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2725: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2726: 	
                   2727: 	if ($submitonly eq 'queued') {
                   2728: 	    my %queue_status = 
                   2729: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2730: 							$udom,$uname);
                   2731: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2732: 	}
                   2733: 
1.156     albertel 2734: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2735: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2736: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2737: 	    my $submitted = 0;
1.248     albertel 2738: 	    my $ungraded = 0;
                   2739: 	    my $incorrect = 0;
1.524     raeburn  2740: 	    foreach my $item (keys(%status)) {
                   2741: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2742: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2743: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2744: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2745: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2746: 		    $submitted = 0;
                   2747: 		}
1.41      ng       2748: 	    }
1.156     albertel 2749: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2750: 				     $submitonly eq 'incorrect' ||
                   2751: 				     $submitonly eq 'graded'));
1.248     albertel 2752: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2753: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2754: 	}
1.524     raeburn  2755: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2756: 	last if ($ctr == $ntstu);
1.41      ng       2757: 	$ctr++;
                   2758:     }
1.36      ng       2759: 
1.41      ng       2760:     $ctr = 0;
                   2761:     my $total = scalar(@nextlist)-1;
1.39      ng       2762: 
1.524     raeburn  2763:     foreach (sort(@nextlist)) {
1.41      ng       2764: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2765: 	$env{'form.student'}  = $uname;
                   2766: 	$env{'form.userdom'}  = $udom;
                   2767: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2768: 	&submission($request,$ctr,$total);
                   2769: 	$ctr++;
                   2770:     }
                   2771:     if ($total < 0) {
1.485     albertel 2772: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2773: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2774: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2775: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2776: 	$request->print($the_end);
                   2777:     }
                   2778:     return '';
1.38      ng       2779: }
1.36      ng       2780: 
1.44      ng       2781: #---- Save the score and award for each student, if changed
1.38      ng       2782: sub saveHandGrade {
1.324     albertel 2783:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2784:     my @version_parts;
1.104     albertel 2785:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2786: 					   $env{'request.course.id'});
1.104     albertel 2787:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2788:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2789:     my @parts_graded;
1.77      ng       2790:     my %newrecord  = ();
                   2791:     my ($pts,$wgt) = ('','');
1.269     raeburn  2792:     my %aggregate = ();
                   2793:     my $aggregateflag = 0;
1.301     albertel 2794:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2795:     foreach my $new_part (@parts) {
1.337     banghart 2796: 	#collaborator ($submi may vary for different parts
1.259     banghart 2797: 	if ($submitter && $new_part ne $part) { next; }
                   2798: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2799: 	if ($dropMenu eq 'excused') {
1.259     banghart 2800: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2801: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2802: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2803: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2804: 		}
1.364     banghart 2805: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2806: 	    }
1.125     ng       2807: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2808: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2809: 	    foreach my $key (keys(%record)) {
1.259     banghart 2810: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2811: 	    }
1.259     banghart 2812: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2813: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2814:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2815: 
                   2816:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2817: 					       [$new_part]);
                   2818:             my $aggtries =$totaltries;
1.269     raeburn  2819:             if ($last_resets{$new_part}) {
1.270     albertel 2820:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2821: 					   $new_part);
1.269     raeburn  2822:             }
1.270     albertel 2823: 
                   2824:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2825:             if ($aggtries > 0) {
1.327     albertel 2826:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2827:                 $aggregateflag = 1;
                   2828:             }
1.125     ng       2829: 	} elsif ($dropMenu eq '') {
1.259     banghart 2830: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2831: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2832: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2833: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2834: 		next;
                   2835: 	    }
1.259     banghart 2836: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2837: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2838: 	    my $partial= $pts/$wgt;
1.259     banghart 2839: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2840: 		#do not update score for part if not changed.
1.346     banghart 2841:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2842: 		next;
1.251     banghart 2843: 	    } else {
1.524     raeburn  2844: 	        push(@parts_graded,$new_part);
1.153     albertel 2845: 	    }
1.259     banghart 2846: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2847: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2848: 	    }
1.259     banghart 2849: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2850: 	    if ($partial == 0) {
1.153     albertel 2851: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2852: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2853: 		}
1.41      ng       2854: 	    } else {
1.153     albertel 2855: 		if ($record{$reckey} ne 'correct_by_override') {
                   2856: 		    $newrecord{$reckey} = 'correct_by_override';
                   2857: 		}
                   2858: 	    }	    
                   2859: 	    if ($submitter && 
1.259     banghart 2860: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2861: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2862: 	    }
1.259     banghart 2863: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2864: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2865: 	}
1.259     banghart 2866: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2867: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2868: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2869: 	        $dropMenu eq 'reset status')
                   2870: 	   {
1.524     raeburn  2871: 	    push(@version_parts,$new_part);
1.259     banghart 2872: 	}
1.41      ng       2873:     }
1.301     albertel 2874:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2875:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2876: 
1.344     albertel 2877:     if (%newrecord) {
                   2878:         if (@version_parts) {
1.364     banghart 2879:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2880:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2881: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2882: 	    foreach my $new_part (@version_parts) {
                   2883: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2884: 				$new_part,\%newrecord);
                   2885: 	    }
1.259     banghart 2886:         }
1.44      ng       2887: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2888: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2889: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2890: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2891:     }
1.269     raeburn  2892:     if ($aggregateflag) {
                   2893:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2894: 			      $cdom,$cnum);
1.269     raeburn  2895:     }
1.301     albertel 2896:     return ('',$pts,$wgt);
1.36      ng       2897: }
1.322     albertel 2898: 
1.380     albertel 2899: sub check_and_remove_from_queue {
                   2900:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2901:     my @ungraded_parts;
                   2902:     foreach my $part (@{$parts}) {
                   2903: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2904: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2905: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2906: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2907: 		) {
                   2908: 	    push(@ungraded_parts, $part);
                   2909: 	}
                   2910:     }
                   2911:     if ( !@ungraded_parts ) {
                   2912: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2913: 					       $cnum,$domain,$stuname);
                   2914:     }
                   2915: }
                   2916: 
1.337     banghart 2917: sub handback_files {
                   2918:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2919:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2920:     my $res_error;
                   2921:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2922:     if ($res_error) {
                   2923:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2924:         return;
                   2925:     }
1.375     albertel 2926:     my @part_response_id = &flatten_responseType($responseType);
                   2927:     foreach my $part_response_id (@part_response_id) {
                   2928:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2929: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2930:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2931:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2932:                 my $file_counter = 1;
1.367     albertel 2933: 		my $file_msg;
1.337     banghart 2934:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2935:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2936:                     my ($directory,$answer_file) = 
                   2937:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2938:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2939: 		        &file_name_version_ext($answer_file);
1.355     banghart 2940: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2941:                     my $getpropath = 1;
                   2942: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2943: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2944:                     # fix file name
                   2945:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2946:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2947:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2948:             	                                $save_file_name);
1.337     banghart 2949:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2950:                         $request->print('<br /><span class="LC_error">'.
                   2951:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2952:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2953:                                         '</span>');
1.356     banghart 2954:                     } else {
1.360     banghart 2955:                         # mark the file as read only
                   2956:                         my @files = ($save_file_name);
1.372     albertel 2957:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2958:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2959: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2960: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2961: 			}
                   2962:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2963: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2964: 
1.337     banghart 2965:                     }
                   2966:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2967:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2968:                     $file_counter++;
                   2969:                 }
1.367     albertel 2970: 		my $subject = "File Handed Back by Instructor ";
                   2971: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2972: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2973: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2974: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2975: 		my ($feedurl,$showsymb) = 
                   2976: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2977:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2978: 		my $msgstatus = 
                   2979:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2980: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2981:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2982:             }
                   2983:         }
1.338     banghart 2984:     return;
1.337     banghart 2985: }
                   2986: 
1.418     albertel 2987: sub get_feedurl_and_symb {
                   2988:     my ($symb,$uname,$udom) = @_;
                   2989:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2990:     $url = &Apache::lonnet::clutter($url);
                   2991:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2992: 					$symb,$udom,$uname);
                   2993:     if ($encrypturl =~ /^yes$/i) {
                   2994: 	&Apache::lonenc::encrypted(\$url,1);
                   2995: 	&Apache::lonenc::encrypted(\$symb,1);
                   2996:     }
                   2997:     return ($url,$symb);
                   2998: }
                   2999: 
1.313     banghart 3000: sub get_submitted_files {
                   3001:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3002:     my @files;
                   3003:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3004:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3005:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3006:     	    push(@files,$file_url.$file);
                   3007:         }
                   3008:     }
                   3009:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3010:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3011:     }
                   3012:     return (\@files);
                   3013: }
1.322     albertel 3014: 
1.269     raeburn  3015: # ----------- Provides number of tries since last reset.
                   3016: sub get_num_tries {
                   3017:     my ($record,$last_reset,$part) = @_;
                   3018:     my $timestamp = '';
                   3019:     my $num_tries = 0;
                   3020:     if ($$record{'version'}) {
                   3021:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3022:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3023:                 $timestamp = $$record{$version.':timestamp'};
                   3024:                 if ($timestamp > $last_reset) {
                   3025:                     $num_tries ++;
                   3026:                 } else {
                   3027:                     last;
                   3028:                 }
                   3029:             }
                   3030:         }
                   3031:     }
                   3032:     return $num_tries;
                   3033: }
                   3034: 
                   3035: # ----------- Determine decrements required in aggregate totals 
                   3036: sub decrement_aggs {
                   3037:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3038:     my %decrement = (
                   3039:                         attempts => 0,
                   3040:                         users => 0,
                   3041:                         correct => 0
                   3042:                     );
                   3043:     $decrement{'attempts'} = $aggtries;
                   3044:     if ($solvedstatus =~ /^correct/) {
                   3045:         $decrement{'correct'} = 1;
                   3046:     }
                   3047:     if ($aggtries == $totaltries) {
                   3048:         $decrement{'users'} = 1;
                   3049:     }
1.524     raeburn  3050:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3051:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3052:     }
                   3053:     return;
                   3054: }
                   3055: 
                   3056: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3057: sub get_last_resets {
1.270     albertel 3058:     my ($symb,$courseid,$partids) =@_;
                   3059:     my %last_resets;
1.269     raeburn  3060:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3061:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3062:     my @keys;
                   3063:     foreach my $part (@{$partids}) {
                   3064: 	push(@keys,"$symb\0$part\0resettime");
                   3065:     }
                   3066:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3067: 				     $cdom,$cname);
                   3068:     foreach my $part (@{$partids}) {
                   3069: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3070:     }
1.270     albertel 3071:     return %last_resets;
1.269     raeburn  3072: }
                   3073: 
1.251     banghart 3074: # ----------- Handles creating versions for portfolio files as answers
                   3075: sub version_portfiles {
1.343     banghart 3076:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3077:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3078:     my @returned_keys;
1.255     banghart 3079:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3080:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3081:     foreach my $key (keys(%$record)) {
1.259     banghart 3082:         my $new_portfiles;
1.263     banghart 3083:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3084:             my @versioned_portfiles;
1.367     albertel 3085:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3086:             foreach my $file (@portfiles) {
1.306     banghart 3087:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3088:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3089: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3090: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3091:                 my $getpropath = 1;    
                   3092:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3093:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3094:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3095:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3096:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3097:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3098:                         [$directory.$new_answer],
1.306     banghart 3099:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3100:                 }
1.252     banghart 3101:             }
1.343     banghart 3102:             $$record{$key} = join(',',@versioned_portfiles);
                   3103:             push(@returned_keys,$key);
1.251     banghart 3104:         }
                   3105:     } 
1.343     banghart 3106:     return (@returned_keys);   
1.305     banghart 3107: }
                   3108: 
1.307     banghart 3109: sub get_next_version {
1.341     banghart 3110:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3111:     my $version;
                   3112:     foreach my $row (@$dir_list) {
                   3113:         my ($file) = split(/\&/,$row,2);
                   3114:         my ($file_name,$file_version,$file_ext) =
                   3115: 	    &file_name_version_ext($file);
                   3116:         if (($file_name eq $answer_name) && 
                   3117: 	    ($file_ext eq $answer_ext)) {
                   3118:                 # gets here if filename and extension match, regardless of version
                   3119:                 if ($file_version ne '') {
                   3120:                 # a versioned file is found  so save it for later
                   3121:                 if ($file_version > $version) {
                   3122: 		    $version = $file_version;
                   3123: 	        }
                   3124:             }
                   3125:         }
                   3126:     } 
                   3127:     $version ++;
                   3128:     return($version);
                   3129: }
                   3130: 
1.305     banghart 3131: sub version_selected_portfile {
1.306     banghart 3132:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3133:     my ($answer_name,$answer_ver,$answer_ext) =
                   3134:         &file_name_version_ext($file_name);
                   3135:     my $new_answer;
                   3136:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3137:     if($env{'form.copy'} eq '-1') {
                   3138:         $new_answer = 'problem getting file';
                   3139:     } else {
                   3140:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3141:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3142:                             $stu_name,$domain,'copy',
                   3143: 		        '/portfolio'.$directory.$new_answer);
                   3144:     }    
                   3145:     return ($new_answer);
1.251     banghart 3146: }
                   3147: 
1.304     albertel 3148: sub file_name_version_ext {
                   3149:     my ($file)=@_;
                   3150:     my @file_parts = split(/\./, $file);
                   3151:     my ($name,$version,$ext);
                   3152:     if (@file_parts > 1) {
                   3153: 	$ext=pop(@file_parts);
                   3154: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3155: 	    $version=pop(@file_parts);
                   3156: 	}
                   3157: 	$name=join('.',@file_parts);
                   3158:     } else {
                   3159: 	$name=join('.',@file_parts);
                   3160:     }
                   3161:     return($name,$version,$ext);
                   3162: }
                   3163: 
1.44      ng       3164: #--------------------------------------------------------------------------------------
                   3165: #
                   3166: #-------------------------- Next few routines handles grading by section or whole class
                   3167: #
                   3168: #--- Javascript to handle grading by section or whole class
1.42      ng       3169: sub viewgrades_js {
                   3170:     my ($request) = shift;
                   3171: 
1.539     riegler  3172:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3173:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3174:    function writePoint(partid,weight,point) {
1.125     ng       3175: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3176: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3177: 	if (point == "textval") {
1.125     ng       3178: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3179: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3180: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3181: 		var resetbox = false;
                   3182: 		for (var i=0; i<radioButton.length; i++) {
                   3183: 		    if (radioButton[i].checked) {
                   3184: 			textbox.value = i;
                   3185: 			resetbox = true;
                   3186: 		    }
                   3187: 		}
                   3188: 		if (!resetbox) {
                   3189: 		    textbox.value = "";
                   3190: 		}
                   3191: 		return;
                   3192: 	    }
1.109     matthew  3193: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3194: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3195: 				   ") greater than the weight for the part. Accept?");
                   3196: 		if (resp == false) {
                   3197: 		    textbox.value = "";
                   3198: 		    return;
                   3199: 		}
                   3200: 	    }
1.42      ng       3201: 	    for (var i=0; i<radioButton.length; i++) {
                   3202: 		radioButton[i].checked=false;
1.109     matthew  3203: 		if (parseFloat(point) == i) {
1.42      ng       3204: 		    radioButton[i].checked=true;
                   3205: 		}
                   3206: 	    }
1.41      ng       3207: 
1.42      ng       3208: 	} else {
1.125     ng       3209: 	    textbox.value = parseFloat(point);
1.42      ng       3210: 	}
1.41      ng       3211: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3212: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3213: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3214: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3215: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3216: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3217: 	    if (saveval != "correct") {
                   3218: 		scorename.value = point;
1.43      ng       3219: 		if (selname[0].selected != true) {
                   3220: 		    selname[0].selected = true;
                   3221: 		}
1.42      ng       3222: 	    }
                   3223: 	}
1.125     ng       3224: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3225:     }
                   3226: 
                   3227:     function writeRadText(partid,weight) {
1.125     ng       3228: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3229: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3230:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3231: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3232: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3233: 	    for (var i=0; i<radioButton.length; i++) {
                   3234: 		radioButton[i].checked=false;
                   3235: 
                   3236: 	    }
                   3237: 	    textbox.value = "";
                   3238: 
                   3239: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3240: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3241: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3242: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3243: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3244: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3245: 		if ((saveval != "correct") || override) {
1.42      ng       3246: 		    scorename.value = "";
1.125     ng       3247: 		    if (selval[1].selected) {
                   3248: 			selname[1].selected = true;
                   3249: 		    } else {
                   3250: 			selname[2].selected = true;
                   3251: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3252: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3253: 		    }
1.42      ng       3254: 		}
                   3255: 	    }
1.43      ng       3256: 	} else {
                   3257: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3258: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3259: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3260: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3261: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3262: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3263: 		if ((saveval != "correct") || override) {
1.125     ng       3264: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3265: 		    selname[0].selected = true;
                   3266: 		}
                   3267: 	    }
                   3268: 	}	    
1.42      ng       3269:     }
                   3270: 
                   3271:     function changeSelect(partid,user) {
1.125     ng       3272: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3273: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3274: 	var point  = textbox.value;
1.125     ng       3275: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3276: 
1.109     matthew  3277: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3278: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3279: 	    textbox.value = "";
                   3280: 	    return;
                   3281: 	}
1.109     matthew  3282: 	if (parseFloat(point) > parseFloat(weight)) {
                   3283: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3284: 			       ") greater than the weight of the part. Accept?");
                   3285: 	    if (resp == false) {
                   3286: 		textbox.value = "";
                   3287: 		return;
                   3288: 	    }
                   3289: 	}
1.42      ng       3290: 	selval[0].selected = true;
                   3291:     }
                   3292: 
                   3293:     function changeOneScore(partid,user) {
1.125     ng       3294: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3295: 	if (selval[1].selected || selval[2].selected) {
                   3296: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3297: 	    if (selval[2].selected) {
                   3298: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3299: 	    }
1.269     raeburn  3300:         }
1.42      ng       3301:     }
                   3302: 
                   3303:     function resetEntry(numpart) {
                   3304: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3305: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3306: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3307: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3308: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3309: 	    for (var i=0; i<radioButton.length; i++) {
                   3310: 		radioButton[i].checked=false;
                   3311: 
                   3312: 	    }
                   3313: 	    textbox.value = "";
                   3314: 	    selval[0].selected = true;
                   3315: 
                   3316: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3317: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3318: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3319: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3320: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3321: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3322: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3323: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3324: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3325: 		if (saveselval == "excused") {
1.43      ng       3326: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3327: 		} else {
1.43      ng       3328: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3329: 		}
                   3330: 	    }
1.41      ng       3331: 	}
1.42      ng       3332:     }
                   3333: 
1.41      ng       3334: VIEWJAVASCRIPT
1.42      ng       3335: }
                   3336: 
1.44      ng       3337: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3338: sub viewgrades {
                   3339:     my ($request) = shift;
                   3340:     &viewgrades_js($request);
1.41      ng       3341: 
1.324     albertel 3342:     my ($symb) = &get_symb($request);
1.168     albertel 3343:     #need to make sure we have the correct data for later EXT calls, 
                   3344:     #thus invalidate the cache
                   3345:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3346:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3347:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3348:     &Apache::lonnet::clear_EXT_cache_status();
                   3349: 
1.398     albertel 3350:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3351:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3352: 
                   3353:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3354:     $result.=&jscriptNform($symb);
1.41      ng       3355: 
1.44      ng       3356:     #beginning of class grading form
1.442     banghart 3357:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3358:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3359: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3360: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3361: 	&build_section_inputs().
1.257     albertel 3362: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3363: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3364: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3365: 
1.560     raeburn  3366:     my ($common_header,$specific_header);
1.257     albertel 3367:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3368: 	$common_header = &mt('Assign Common Grade to Class');
                   3369:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3370:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3371:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3372: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3373:     } else {
1.560     raeburn  3374:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3375:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3376: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3377:     }
1.560     raeburn  3378:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3379:     #radio buttons/text box for assigning points for a section or class.
                   3380:     #handles different parts of a problem
1.582     raeburn  3381:     my $res_error;
                   3382:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3383:     if ($res_error) {
                   3384:         return &navmap_errormsg();
                   3385:     }
1.42      ng       3386:     my %weight = ();
                   3387:     my $ctsparts = 0;
1.45      ng       3388:     my %seen = ();
1.375     albertel 3389:     my @part_response_id = &flatten_responseType($responseType);
                   3390:     foreach my $part_response_id (@part_response_id) {
                   3391:     	my ($partid,$respid) = @{ $part_response_id };
                   3392: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3393: 	next if $seen{$partid};
                   3394: 	$seen{$partid}++;
1.375     albertel 3395: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3396: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3397: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3398: 
1.324     albertel 3399: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3400: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3401: 	my $ctr = 0;
1.42      ng       3402: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3403: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3404: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3405: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3406: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3407: 	    $ctr++;
                   3408: 	}
1.485     albertel 3409: 	$radio.='</tr></table>';
                   3410: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3411: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3412: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3413: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3414: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3415: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3416: 		$weight{$partid}.')"> '.
1.401     albertel 3417: 	    '<option selected="selected"> </option>'.
1.485     albertel 3418: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3419: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3420: 	    '</select></td>'.
                   3421:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3422: 	$line.='<input type="hidden" name="partid_'.
                   3423: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3424: 	$line.='<input type="hidden" name="weight_'.
                   3425: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3426: 
                   3427: 	$result.=
                   3428: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3429: 	    '<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 3430: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3431: 	$ctsparts++;
1.41      ng       3432:     }
1.474     albertel 3433:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3434: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3435:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3436: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3437: 
1.44      ng       3438:     #table listing all the students in a section/class
                   3439:     #header of table
1.560     raeburn  3440:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3441:               &Apache::loncommon::start_data_table().
                   3442: 	      &Apache::loncommon::start_data_table_header_row().
                   3443: 	      '<th>'.&mt('No.').'</th>'.
                   3444: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3445:     my $partserror;
                   3446:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3447:     if ($partserror) {
                   3448:         return &navmap_errormsg();
                   3449:     }
1.324     albertel 3450:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3451:     my @partids = ();
1.41      ng       3452:     foreach my $part (@parts) {
                   3453: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3454:         my $narrowtext = &mt('Tries');
                   3455: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3456: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3457: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3458:         push(@partids,$partid);
1.324     albertel 3459: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3460: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3461: 	    $result.='<th>'.
                   3462: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3463: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3464: 	    next;
1.485     albertel 3465: 	    
1.207     albertel 3466: 	} else {
1.485     albertel 3467: 	    if ($display =~ /Problem Status/) {
                   3468: 		my $grade_status_mt = &mt('Grade Status');
                   3469: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3470: 	    }
                   3471: 	    my $part_mt = &mt('Part:');
                   3472: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3473: 	}
1.485     albertel 3474: 
1.474     albertel 3475: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3476:     }
1.474     albertel 3477:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3478: 
1.270     albertel 3479:     my %last_resets = 
                   3480: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3481: 
1.41      ng       3482:     #get info for each student
1.44      ng       3483:     #list all the students - with points and grade status
1.257     albertel 3484:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3485:     my $ctr = 0;
1.294     albertel 3486:     foreach (sort 
                   3487: 	     {
                   3488: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3489: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3490: 		 }
                   3491: 		 return $a cmp $b;
                   3492: 	     } (keys(%$fullname))) {
1.126     ng       3493: 	$ctr++;
1.324     albertel 3494: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3495: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3496:     }
1.474     albertel 3497:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3498:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3499:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3500: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3501:     if (scalar(%$fullname) eq 0) {
                   3502: 	my $colspan=3+scalar(@parts);
1.433     banghart 3503: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3504:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3505: 	$result='<span class="LC_warning">'.
1.485     albertel 3506: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3507: 	        $section_display, $stu_status).
1.433     banghart 3508: 	    '</span>';
1.96      albertel 3509:     }
1.324     albertel 3510:     $result.=&show_grading_menu_form($symb);
1.41      ng       3511:     return $result;
                   3512: }
                   3513: 
1.44      ng       3514: #--- call by previous routine to display each student
1.41      ng       3515: sub viewstudentgrade {
1.324     albertel 3516:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3517:     my ($uname,$udom) = split(/:/,$student);
                   3518:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3519:     my %aggregates = (); 
1.474     albertel 3520:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3521: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3522: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3523: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3524: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3525: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3526:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3527:     foreach my $apart (@$parts) {
                   3528: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3529: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3530:         $result.='<td align="center">';
1.269     raeburn  3531:         my ($aggtries,$totaltries);
                   3532:         unless (exists($aggregates{$part})) {
1.270     albertel 3533: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3534: 
                   3535: 	    $aggtries = $totaltries;
1.269     raeburn  3536:             if ($$last_resets{$part}) {  
1.270     albertel 3537:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3538: 					   $part);
                   3539:             }
1.269     raeburn  3540:             $result.='<input type="hidden" name="'.
                   3541:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3542:             $result.='<input type="hidden" name="'.
                   3543:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3544:             $aggregates{$part} = 1;
                   3545:         }
1.41      ng       3546: 	if ($type eq 'awarded') {
1.320     albertel 3547: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3548: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3549: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3550: 	    $result.='<input type="text" name="'.
1.89      albertel 3551: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3552:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3553: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3554: 	} elsif ($type eq 'solved') {
                   3555: 	    my ($status,$foo)=split(/_/,$score,2);
                   3556: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3557: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3558: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3559: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3560: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3561:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3562: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3563: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3564: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3565: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3566: 	} else {
                   3567: 	    $result.='<input type="hidden" name="'.
                   3568: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3569: 		    "\n";
1.233     albertel 3570: 	    $result.='<input type="text" name="'.
1.122     ng       3571: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3572: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3573: 	}
                   3574:     }
1.474     albertel 3575:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3576:     return $result;
1.38      ng       3577: }
                   3578: 
1.44      ng       3579: #--- change scores for all the students in a section/class
                   3580: #    record does not get update if unchanged
1.38      ng       3581: sub editgrades {
1.41      ng       3582:     my ($request) = @_;
                   3583: 
1.324     albertel 3584:     my $symb=&get_symb($request);
1.433     banghart 3585:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3586:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3587:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3588:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3589: 
1.477     albertel 3590:     my $result= &Apache::loncommon::start_data_table().
                   3591: 	&Apache::loncommon::start_data_table_header_row().
                   3592: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3593: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3594:     my %scoreptr = (
                   3595: 		    'correct'  =>'correct_by_override',
                   3596: 		    'incorrect'=>'incorrect_by_override',
                   3597: 		    'excused'  =>'excused',
                   3598: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3599:                     'credited' =>'credit_attempted',
1.43      ng       3600: 		    'nothing'  => '',
                   3601: 		    );
1.257     albertel 3602:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3603: 
1.44      ng       3604:     my (@partid);
                   3605:     my %weight = ();
1.54      albertel 3606:     my %columns = ();
1.44      ng       3607:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3608: 
1.582     raeburn  3609:     my $partserror;
                   3610:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3611:     if ($partserror) {
                   3612:         return &navmap_errormsg();
                   3613:     }
1.54      albertel 3614:     my $header;
1.257     albertel 3615:     while ($ctr < $env{'form.totalparts'}) {
                   3616: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3617: 	push(@partid,$partid);
1.257     albertel 3618: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3619: 	$ctr++;
1.54      albertel 3620:     }
1.324     albertel 3621:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3622:     foreach my $partid (@partid) {
1.478     albertel 3623: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3624: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3625: 	$columns{$partid}=2;
                   3626: 	foreach my $stores (@parts) {
                   3627: 	    my ($part,$type) = &split_part_type($stores);
                   3628: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3629: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3630: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3631: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3632:             my $narrowtext = &mt('Tries');
                   3633: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3634: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3635: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3636: 	    $columns{$partid}+=2;
                   3637: 	}
                   3638:     }
                   3639:     foreach my $partid (@partid) {
1.324     albertel 3640: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3641: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3642: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3643: 	    '</th>';
1.54      albertel 3644: 
1.44      ng       3645:     }
1.477     albertel 3646:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3647: 	&Apache::loncommon::start_data_table_header_row().
                   3648: 	$header.
                   3649: 	&Apache::loncommon::end_data_table_header_row();
                   3650:     my @noupdate;
1.126     ng       3651:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3652:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3653: 	my $line;
1.257     albertel 3654: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3655: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3656: 	my %newrecord;
                   3657: 	my $updateflag = 0;
1.281     albertel 3658: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3659: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3660: 	if (!&canmodify($usec)) {
1.126     ng       3661: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3662: 	    push(@noupdate,
1.478     albertel 3663: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3664: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3665: 	    next;
                   3666: 	}
1.269     raeburn  3667:         my %aggregate = ();
                   3668:         my $aggregateflag = 0;
1.281     albertel 3669: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3670: 	foreach (@partid) {
1.257     albertel 3671: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3672: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3673: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3674: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3675: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3676: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3677: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3678: 	    my $score;
                   3679: 	    if ($partial eq '') {
1.257     albertel 3680: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3681: 	    } elsif ($partial > 0) {
                   3682: 		$score = 'correct_by_override';
                   3683: 	    } elsif ($partial == 0) {
                   3684: 		$score = 'incorrect_by_override';
                   3685: 	    }
1.257     albertel 3686: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3687: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3688: 
1.292     albertel 3689: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3690: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3691: 	    if ($dropMenu eq 'reset status' &&
                   3692: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3693: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3694: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3695: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3696: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3697: 		$updateflag = 1;
1.269     raeburn  3698:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3699:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3700:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3701:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3702:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3703:                     $aggregateflag = 1;
                   3704:                 }
1.139     albertel 3705: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3706: 		$updateflag = 1;
                   3707: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3708: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3709: 		$rec_update++;
1.125     ng       3710: 	    }
                   3711: 
1.93      albertel 3712: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3713: 		'<td align="center">'.$awarded.
                   3714: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3715: 
1.54      albertel 3716: 
                   3717: 	    my $partid=$_;
                   3718: 	    foreach my $stores (@parts) {
                   3719: 		my ($part,$type) = &split_part_type($stores);
                   3720: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3721: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3722: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3723: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3724: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3725: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3726: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3727: 		    $updateflag=1;
                   3728: 		}
1.93      albertel 3729: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3730: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3731: 	    }
1.44      ng       3732: 	}
1.477     albertel 3733: 	$line.="\n";
1.301     albertel 3734: 
                   3735: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3736: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3737: 
1.44      ng       3738: 	if ($updateflag) {
                   3739: 	    $count++;
1.257     albertel 3740: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3741: 				    $udom,$uname);
1.301     albertel 3742: 
                   3743: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3744: 					      $cnum,$udom,$uname)) {
                   3745: 		# need to figure out if should be in queue.
                   3746: 		my %record =  
                   3747: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3748: 					     $udom,$uname);
                   3749: 		my $all_graded = 1;
                   3750: 		my $none_graded = 1;
                   3751: 		foreach my $part (@parts) {
                   3752: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3753: 			$all_graded = 0;
                   3754: 		    } else {
                   3755: 			$none_graded = 0;
                   3756: 		    }
                   3757: 		}
                   3758: 
                   3759: 		if ($all_graded || $none_graded) {
                   3760: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3761: 							   $symb,$cdom,$cnum,
                   3762: 							   $udom,$uname);
                   3763: 		}
                   3764: 	    }
                   3765: 
1.477     albertel 3766: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3767: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3768: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3769: 	    $updateCtr++;
1.93      albertel 3770: 	} else {
1.477     albertel 3771: 	    push(@noupdate,
                   3772: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3773: 	    $noupdateCtr++;
1.44      ng       3774: 	}
1.269     raeburn  3775:         if ($aggregateflag) {
                   3776:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3777: 				  $cdom,$cnum);
1.269     raeburn  3778:         }
1.93      albertel 3779:     }
1.477     albertel 3780:     if (@noupdate) {
1.126     ng       3781: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3782: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3783: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3784: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3785: 	    &mt('No Changes Occurred For the Students Below').
                   3786: 	    '</td>'.
1.477     albertel 3787: 	    &Apache::loncommon::end_data_table_row();
                   3788: 	foreach my $line (@noupdate) {
                   3789: 	    $result.=
                   3790: 		&Apache::loncommon::start_data_table_row().
                   3791: 		$line.
                   3792: 		&Apache::loncommon::end_data_table_row();
                   3793: 	}
1.44      ng       3794:     }
1.477     albertel 3795:     $result .= &Apache::loncommon::end_data_table().
                   3796: 	&show_grading_menu_form($symb);
1.478     albertel 3797:     my $msg = '<p><b>'.
                   3798: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3799: 	    $rec_update,$count).'</b><br />'.
                   3800: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3801: 	'</b></p>';
1.44      ng       3802:     return $title.$msg.$result;
1.5       albertel 3803: }
1.54      albertel 3804: 
                   3805: sub split_part_type {
                   3806:     my ($partstr) = @_;
                   3807:     my ($temp,@allparts)=split(/_/,$partstr);
                   3808:     my $type=pop(@allparts);
1.439     albertel 3809:     my $part=join('_',@allparts);
1.54      albertel 3810:     return ($part,$type);
                   3811: }
                   3812: 
1.44      ng       3813: #------------- end of section for handling grading by section/class ---------
                   3814: #
                   3815: #----------------------------------------------------------------------------
                   3816: 
1.5       albertel 3817: 
1.44      ng       3818: #----------------------------------------------------------------------------
                   3819: #
                   3820: #-------------------------- Next few routines handles grading by csv upload
                   3821: #
                   3822: #--- Javascript to handle csv upload
1.27      albertel 3823: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3824:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3825:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3826:   return(<<ENDPICK);
                   3827:   function verify(vf) {
                   3828:     var foundsomething=0;
                   3829:     var founduname=0;
1.243     albertel 3830:     var foundID=0;
1.27      albertel 3831:     for (i=0;i<=vf.nfields.value;i++) {
                   3832:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3833:       if (i==0 && tw!=0) { foundID=1; }
                   3834:       if (i==1 && tw!=0) { founduname=1; }
                   3835:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3836:     }
1.246     albertel 3837:     if (founduname==0 && foundID==0) {
                   3838: 	alert('$error1');
                   3839: 	return;
1.27      albertel 3840:     }
                   3841:     if (foundsomething==0) {
1.246     albertel 3842: 	alert('$error2');
                   3843: 	return;
1.27      albertel 3844:     }
                   3845:     vf.submit();
                   3846:   }
                   3847:   function flip(vf,tf) {
                   3848:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3849:     var i;
                   3850:     for (i=0;i<=vf.nfields.value;i++) {
                   3851:       //can not pick the same destination field for both name and domain
                   3852:       if (((i ==0)||(i ==1)) && 
                   3853:           ((tf==0)||(tf==1)) && 
                   3854:           (i!=tf) &&
                   3855:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3856:         eval('vf.f'+i+'.selectedIndex=0;')
                   3857:       }
                   3858:     }
                   3859:   }
                   3860: ENDPICK
                   3861: }
                   3862: 
                   3863: sub csvupload_javascript_forward_associate {
1.573     bisitz   3864:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3865:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3866:   return(<<ENDPICK);
                   3867:   function verify(vf) {
                   3868:     var foundsomething=0;
                   3869:     var founduname=0;
1.243     albertel 3870:     var foundID=0;
1.27      albertel 3871:     for (i=0;i<=vf.nfields.value;i++) {
                   3872:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3873:       if (tw==1) { foundID=1; }
                   3874:       if (tw==2) { founduname=1; }
                   3875:       if (tw>3) { foundsomething=1; }
1.27      albertel 3876:     }
1.246     albertel 3877:     if (founduname==0 && foundID==0) {
                   3878: 	alert('$error1');
                   3879: 	return;
1.27      albertel 3880:     }
                   3881:     if (foundsomething==0) {
1.246     albertel 3882: 	alert('$error2');
                   3883: 	return;
1.27      albertel 3884:     }
                   3885:     vf.submit();
                   3886:   }
                   3887:   function flip(vf,tf) {
                   3888:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3889:     var i;
                   3890:     //can not pick the same destination field twice
                   3891:     for (i=0;i<=vf.nfields.value;i++) {
                   3892:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3893:         eval('vf.f'+i+'.selectedIndex=0;')
                   3894:       }
                   3895:     }
                   3896:   }
                   3897: ENDPICK
                   3898: }
                   3899: 
1.26      albertel 3900: sub csvuploadmap_header {
1.324     albertel 3901:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3902:     my $javascript;
1.257     albertel 3903:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3904: 	$javascript=&csvupload_javascript_reverse_associate();
                   3905:     } else {
                   3906: 	$javascript=&csvupload_javascript_forward_associate();
                   3907:     }
1.45      ng       3908: 
1.598   ! www      3909: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
        !          3910:     my $result='';
1.257     albertel 3911:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3912:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3913:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3914:     $request->print(<<ENDPICK);
1.26      albertel 3915: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3916: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3917: $result
1.326     albertel 3918: <hr />
1.26      albertel 3919: <h3>Identify fields</h3>
                   3920: Total number of records found in file: $distotal <hr />
                   3921: Enter as many fields as you can. The system will inform you and bring you back
                   3922: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3923: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3924: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3925: <input type="hidden" name="associate"  value="" />
                   3926: <input type="hidden" name="phase"      value="three" />
                   3927: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3928: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3929: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3930: <input type="hidden" name="upfile_associate" 
1.257     albertel 3931:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3932: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3933: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3934: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3935: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3936: <hr />
                   3937: ENDPICK
1.597     wenzelju 3938:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3939:     return '';
1.26      albertel 3940: 
                   3941: }
                   3942: 
                   3943: sub csvupload_fields {
1.582     raeburn  3944:     my ($symb,$errorref) = @_;
                   3945:     my (@parts) = &getpartlist($symb,$errorref);
                   3946:     if (ref($errorref)) {
                   3947:         if ($$errorref) {
                   3948:             return;
                   3949:         }
                   3950:     }
                   3951: 
1.556     weissno  3952:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3953: 		['username','Student Username'],
                   3954: 		['domain','Student Domain']);
1.324     albertel 3955:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3956:     foreach my $part (sort(@parts)) {
                   3957: 	my @datum;
                   3958: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3959: 	my $name=$part;
                   3960: 	if  (!$display) { $display = $name; }
                   3961: 	@datum=($name,$display);
1.244     albertel 3962: 	if ($name=~/^stores_(.*)_awarded/) {
                   3963: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3964: 	}
1.41      ng       3965: 	push(@fields,\@datum);
                   3966:     }
                   3967:     return (@fields);
1.26      albertel 3968: }
                   3969: 
                   3970: sub csvuploadmap_footer {
1.41      ng       3971:     my ($request,$i,$keyfields) =@_;
                   3972:     $request->print(<<ENDPICK);
1.26      albertel 3973: </table>
                   3974: <input type="hidden" name="nfields" value="$i" />
                   3975: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3976: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3977: </form>
                   3978: ENDPICK
                   3979: }
                   3980: 
1.283     albertel 3981: sub checkforfile_js {
1.539     riegler  3982:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3983:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3984:     function checkUpload(formname) {
                   3985: 	if (formname.upfile.value == "") {
1.539     riegler  3986: 	    alert("$alertmsg");
1.86      ng       3987: 	    return false;
                   3988: 	}
                   3989: 	formname.submit();
                   3990:     }
                   3991: CSVFORMJS
1.283     albertel 3992:     return $result;
                   3993: }
                   3994: 
                   3995: sub upcsvScores_form {
                   3996:     my ($request) = shift;
1.324     albertel 3997:     my ($symb)=&get_symb($request);
1.283     albertel 3998:     if (!$symb) {return '';}
                   3999:     my $result=&checkforfile_js();
1.257     albertel 4000:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.598   ! www      4001: #    my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
        !          4002: #    $result.=$table;
1.326     albertel 4003:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   4004:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 4005:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   4006: 	'</b></td></tr>'."\n";
1.86      ng       4007:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      4008:     my $upload=&mt("Upload Scores");
1.86      ng       4009:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4010:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4011:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4012:     $result.=<<ENDUPFORM;
1.106     albertel 4013: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4014: <input type="hidden" name="symb" value="$symb" />
                   4015: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4016: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4017: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4018: $upfile_select
1.589     bisitz   4019: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4020: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4021: </form>
                   4022: ENDUPFORM
1.370     www      4023:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4024:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4025:     .'</td></tr></table>'."\n";
1.86      ng       4026:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4027:     $result.=&show_grading_menu_form($symb);
1.86      ng       4028:     return $result;
                   4029: }
                   4030: 
                   4031: 
1.26      albertel 4032: sub csvuploadmap {
1.41      ng       4033:     my ($request)= @_;
1.324     albertel 4034:     my ($symb)=&get_symb($request);
1.41      ng       4035:     if (!$symb) {return '';}
1.72      ng       4036: 
1.41      ng       4037:     my $datatoken;
1.257     albertel 4038:     if (!$env{'form.datatoken'}) {
1.41      ng       4039: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4040:     } else {
1.257     albertel 4041: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4042: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4043:     }
1.41      ng       4044:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4045:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4046:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4047:     my ($i,$keyfields);
                   4048:     if (@records) {
1.582     raeburn  4049:         my $fieldserror;
                   4050: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4051:         if ($fieldserror) {
                   4052:             $request->print(&navmap_errormsg());
                   4053:             return;
                   4054:         }
1.257     albertel 4055: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4056: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4057: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4058: 							  \@fields);
                   4059: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4060: 	    chop($keyfields);
                   4061: 	} else {
                   4062: 	    unshift(@fields,['none','']);
                   4063: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4064: 							    \@fields);
1.311     banghart 4065:             foreach my $rec (@records) {
                   4066:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4067:                 if (%temp) {
                   4068:                     $keyfields=join(',',sort(keys(%temp)));
                   4069:                     last;
                   4070:                 }
                   4071:             }
1.41      ng       4072: 	}
                   4073:     }
                   4074:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4075:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4076: 
1.41      ng       4077:     return '';
1.27      albertel 4078: }
                   4079: 
1.246     albertel 4080: sub csvuploadoptions {
1.41      ng       4081:     my ($request)= @_;
1.324     albertel 4082:     my ($symb)=&get_symb($request);
1.257     albertel 4083:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4084:     my $ignore=&mt('Ignore First Line');
                   4085:     $request->print(<<ENDPICK);
                   4086: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4087: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4088: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4089: <!--
1.246     albertel 4090: <p>
                   4091: <label>
                   4092:    <input type="checkbox" name="show_full_results" />
                   4093:    Show a table of all changes
                   4094: </label>
                   4095: </p>
1.302     albertel 4096: -->
1.246     albertel 4097: <p>
                   4098: <label>
                   4099:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4100:    Overwrite any existing score
                   4101: </label>
                   4102: </p>
                   4103: ENDPICK
                   4104:     my %fields=&get_fields();
                   4105:     if (!defined($fields{'domain'})) {
1.257     albertel 4106: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4107: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4108:     }
1.257     albertel 4109:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4110: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4111: 	my $cleankey=$1;
                   4112: 	if ($cleankey eq 'command') { next; }
                   4113: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4114: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4115:     }
                   4116:     # FIXME do a check for any duplicated user ids...
                   4117:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4118:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4119: <hr /></form>'."\n");
1.324     albertel 4120:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4121:     return '';
                   4122: }
                   4123: 
                   4124: sub get_fields {
                   4125:     my %fields;
1.257     albertel 4126:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4127:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4128: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4129: 	    if ($env{'form.f'.$i} ne 'none') {
                   4130: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4131: 	    }
                   4132: 	} else {
1.257     albertel 4133: 	    if ($env{'form.f'.$i} ne 'none') {
                   4134: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4135: 	    }
                   4136: 	}
1.27      albertel 4137:     }
1.246     albertel 4138:     return %fields;
                   4139: }
                   4140: 
                   4141: sub csvuploadassign {
                   4142:     my ($request)= @_;
1.324     albertel 4143:     my ($symb)=&get_symb($request);
1.246     albertel 4144:     if (!$symb) {return '';}
1.345     bowersj2 4145:     my $error_msg = '';
1.246     albertel 4146:     &Apache::loncommon::load_tmp_file($request);
                   4147:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4148:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4149:     my %fields=&get_fields();
1.41      ng       4150:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4151:     my $courseid=$env{'request.course.id'};
1.97      albertel 4152:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4153:     my @notallowed;
1.41      ng       4154:     my @skipped;
                   4155:     my $countdone=0;
                   4156:     foreach my $grade (@gradedata) {
                   4157: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4158: 	my $domain;
                   4159: 	if ($entries{$fields{'domain'}}) {
                   4160: 	    $domain=$entries{$fields{'domain'}};
                   4161: 	} else {
1.257     albertel 4162: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4163: 	}
1.243     albertel 4164: 	$domain=~s/\s//g;
1.41      ng       4165: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4166: 	$username=~s/\s//g;
1.243     albertel 4167: 	if (!$username) {
                   4168: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4169: 	    $id=~s/\s//g;
1.243     albertel 4170: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4171: 	    $username=$ids{$id};
                   4172: 	}
1.41      ng       4173: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4174: 	    my $id=$entries{$fields{'ID'}};
                   4175: 	    $id=~s/\s//g;
                   4176: 	    if ($id) {
                   4177: 		push(@skipped,"$id:$domain");
                   4178: 	    } else {
                   4179: 		push(@skipped,"$username:$domain");
                   4180: 	    }
1.41      ng       4181: 	    next;
                   4182: 	}
1.108     albertel 4183: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4184: 	if (!&canmodify($usec)) {
                   4185: 	    push(@notallowed,"$username:$domain");
                   4186: 	    next;
                   4187: 	}
1.244     albertel 4188: 	my %points;
1.41      ng       4189: 	my %grades;
                   4190: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4191: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4192: 		$dest eq 'domain') { next; }
                   4193: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4194: 	    if ($dest=~/stores_(.*)_points/) {
                   4195: 		my $part=$1;
                   4196: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4197: 					      $symb,$domain,$username);
1.345     bowersj2 4198:                 if ($wgt) {
                   4199:                     $entries{$fields{$dest}}=~s/\s//g;
                   4200:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4201:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4202:                                           : 'correct_by_override';
1.345     bowersj2 4203:                     $grades{"resource.$part.awarded"}=$pcr;
                   4204:                     $grades{"resource.$part.solved"}=$award;
                   4205:                     $points{$part}=1;
                   4206:                 } else {
                   4207:                     $error_msg = "<br />" .
                   4208:                         &mt("Some point values were assigned"
                   4209:                             ." for problems with a weight "
                   4210:                             ."of zero. These values were "
                   4211:                             ."ignored.");
                   4212:                 }
1.244     albertel 4213: 	    } else {
                   4214: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4215: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4216: 		my $store_key=$dest;
                   4217: 		$store_key=~s/^stores/resource/;
                   4218: 		$store_key=~s/_/\./g;
                   4219: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4220: 	    }
1.41      ng       4221: 	}
1.508     www      4222: 	if (! %grades) { 
                   4223:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4224:         } else {
                   4225: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4226: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4227: 					   $env{'request.course.id'},
                   4228: 					   $domain,$username);
1.508     www      4229: 	   if ($result eq 'ok') {
                   4230: 	      $request->print('.');
                   4231: 	   } else {
                   4232: 	      $request->print("<p><span class=\"LC_error\">".
                   4233:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4234:                                   "$username:$domain",$result)."</span></p>");
                   4235: 	   }
                   4236: 	   $request->rflush();
                   4237: 	   $countdone++;
                   4238:         }
1.41      ng       4239:     }
1.570     www      4240:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4241:     if (@skipped) {
1.571     www      4242: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4243:         $request->print(join(', ',@skipped));
1.106     albertel 4244:     }
                   4245:     if (@notallowed) {
1.571     www      4246: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4247: 	$request->print(join(', ',@notallowed));
1.41      ng       4248:     }
1.106     albertel 4249:     $request->print("<br />\n");
1.324     albertel 4250:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4251:     return $error_msg;
1.26      albertel 4252: }
1.44      ng       4253: #------------- end of section for handling csv file upload ---------
                   4254: #
                   4255: #-------------------------------------------------------------------
                   4256: #
1.122     ng       4257: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4258: #
                   4259: #--- Select a page/sequence and a student to grade
1.68      ng       4260: sub pickStudentPage {
                   4261:     my ($request) = shift;
                   4262: 
1.539     riegler  4263:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4264:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4265: 
                   4266: function checkPickOne(formname) {
1.76      ng       4267:     if (radioSelection(formname.student) == null) {
1.539     riegler  4268: 	alert("$alertmsg");
1.68      ng       4269: 	return;
                   4270:     }
1.125     ng       4271:     ptr = pullDownSelection(formname.selectpage);
                   4272:     formname.page.value = formname["page"+ptr].value;
                   4273:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4274:     formname.submit();
                   4275: }
                   4276: 
                   4277: LISTJAVASCRIPT
1.118     ng       4278:     &commonJSfunctions($request);
1.324     albertel 4279:     my ($symb) = &get_symb($request);
1.257     albertel 4280:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4281:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4282:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4283: 
1.398     albertel 4284:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4285: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4286: 
1.80      ng       4287:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4288:     my $map_error;
                   4289:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4290:     if ($map_error) {
                   4291:         $request->print(&navmap_errormsg());
                   4292:         return; 
                   4293:     }
1.137     albertel 4294:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4295: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4296: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4297:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4298:     my $ctr=0;
1.68      ng       4299:     foreach (@$titles) {
                   4300: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4301: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4302: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4303: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4304: 	$ctr++;
1.68      ng       4305:     }
1.485     albertel 4306:     $select.= '</select>';
1.539     riegler  4307:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4308: 
1.70      ng       4309:     $ctr=0;
                   4310:     foreach (@$titles) {
                   4311: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4312: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4313: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4314: 	$ctr++;
                   4315:     }
1.72      ng       4316:     $result.='<input type="hidden" name="page" />'."\n".
                   4317: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4318: 
1.485     albertel 4319:     my $options =
                   4320: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4321: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4322:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4323: 
                   4324:     $options =
                   4325: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4326: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4327: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4328:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4329:     
                   4330:     $result.=&build_section_inputs();
1.442     banghart 4331:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4332:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4333: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4334: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4335: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4336: 
1.539     riegler  4337:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4338: 
1.80      ng       4339:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4340:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4341: 
1.68      ng       4342:     $request->print($result);
                   4343: 
1.485     albertel 4344:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4345: 	&Apache::loncommon::start_data_table().
                   4346: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4347: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4348: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4349: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4350: 	'<th>'.&nameUserString('header').'</th>'.
                   4351: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4352:  
1.76      ng       4353:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4354:     my $ptr = 1;
1.294     albertel 4355:     foreach my $student (sort 
                   4356: 			 {
                   4357: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4358: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4359: 			     }
                   4360: 			     return $a cmp $b;
                   4361: 			 } (keys(%$fullname))) {
1.68      ng       4362: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4363: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4364:                                   : '</td>');
1.126     ng       4365: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4366: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4367: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4368: 	$studentTable.=
                   4369: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4370:                          : '');
1.68      ng       4371: 	$ptr++;
                   4372:     }
1.484     albertel 4373:     if ($ptr%2 == 0) {
                   4374: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4375: 	    &Apache::loncommon::end_data_table_row();
                   4376:     }
                   4377:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4378:     $studentTable.='<input type="button" '.
1.589     bisitz   4379:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4380: 
1.324     albertel 4381:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4382:     $request->print($studentTable);
                   4383: 
                   4384:     return '';
                   4385: }
                   4386: 
                   4387: sub getSymbMap {
1.582     raeburn  4388:     my ($map_error) = @_;
1.132     bowersj2 4389:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4390:     unless (ref($navmap)) {
                   4391:         if (ref($map_error)) {
                   4392:             $$map_error = 'navmap';
                   4393:         }
                   4394:         return;
                   4395:     }
1.68      ng       4396:     my %symbx = ();
                   4397:     my @titles = ();
1.117     bowersj2 4398:     my $minder = 0;
                   4399: 
                   4400:     # Gather every sequence that has problems.
1.240     albertel 4401:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4402: 					       1,0,1);
1.117     bowersj2 4403:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4404: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4405: 	    my $title = $minder.'.'.
                   4406: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4407: 	    push(@titles, $title); # minder in case two titles are identical
                   4408: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4409: 	    $minder++;
1.241     albertel 4410: 	}
1.68      ng       4411:     }
                   4412:     return \@titles,\%symbx;
                   4413: }
                   4414: 
1.72      ng       4415: #
                   4416: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4417: sub displayPage {
                   4418:     my ($request) = shift;
                   4419: 
1.324     albertel 4420:     my ($symb) = &get_symb($request);
1.257     albertel 4421:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4422:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4423:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4424:     my $pageTitle = $env{'form.page'};
1.103     albertel 4425:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4426:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4427:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4428: 
                   4429:     #need to make sure we have the correct data for later EXT calls, 
                   4430:     #thus invalidate the cache
                   4431:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4432:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4433:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4434:     &Apache::lonnet::clear_EXT_cache_status();
                   4435: 
1.103     albertel 4436:     if (!&canview($usec)) {
1.485     albertel 4437: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4438: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4439: 	return;
                   4440:     }
1.398     albertel 4441:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4442:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4443: 	'</h3>'."\n";
1.500     albertel 4444:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4445:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4446: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4447:     } else {
                   4448: 	delete($env{'form.CODE'});
                   4449:     }
1.71      ng       4450:     &sub_page_js($request);
                   4451:     $request->print($result);
                   4452: 
1.132     bowersj2 4453:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4454:     unless (ref($navmap)) {
                   4455:         $request->print(&navmap_errormsg());
                   4456:         $request->print(&show_grading_menu_form($symb));
                   4457:         return;
                   4458:     }
1.257     albertel 4459:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4460:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4461:     if (!$map) {
1.485     albertel 4462: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4463: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4464: 	return; 
                   4465:     }
1.68      ng       4466:     my $iterator = $navmap->getIterator($map->map_start(),
                   4467: 					$map->map_finish());
                   4468: 
1.71      ng       4469:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4470: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4471: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4472: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4473: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4474: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4475: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4476: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4477: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4478: 
1.382     albertel 4479:     if (defined($env{'form.CODE'})) {
                   4480: 	$studentTable.=
                   4481: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4482:     }
1.381     albertel 4483:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4484: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4485: 
1.594     bisitz   4486:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4487:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4488:         '</span>'."\n".
1.484     albertel 4489: 	&Apache::loncommon::start_data_table().
                   4490: 	&Apache::loncommon::start_data_table_header_row().
                   4491: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4492: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4493: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4494: 
1.329     albertel 4495:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4496:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4497:     $iterator->next(); # skip the first BEGIN_MAP
                   4498:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4499:     while ($depth > 0) {
1.68      ng       4500:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4501:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4502: 
1.385     albertel 4503:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4504: 	    my $parts = $curRes->parts();
1.68      ng       4505:             my $title = $curRes->compTitle();
1.71      ng       4506: 	    my $symbx = $curRes->symb();
1.484     albertel 4507: 	    $studentTable.=
                   4508: 		&Apache::loncommon::start_data_table_row().
                   4509: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4510: 		(scalar(@{$parts}) == 1 ? '' 
                   4511: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4512: 							scalar(@{$parts}))
                   4513: 		 ).
                   4514: 		 '</td>';
1.71      ng       4515: 	    $studentTable.='<td valign="top">';
1.382     albertel 4516: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4517: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4518: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4519: 					     undef,'both',\%form);
1.71      ng       4520: 	    } else {
1.382     albertel 4521: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4522: 		$companswer =~ s|<form(.*?)>||g;
                   4523: 		$companswer =~ s|</form>||g;
1.71      ng       4524: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4525: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4526: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4527: #		}
1.116     ng       4528: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4529: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4530: 	    }
                   4531: 
1.257     albertel 4532: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4533: 
1.257     albertel 4534: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4535: 		if ($record{'version'} eq '') {
1.485     albertel 4536: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4537: 		} else {
1.116     ng       4538: 		    my %responseType = ();
                   4539: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4540: 			my @responseIds =$curRes->responseIds($partid);
                   4541: 			my @responseType =$curRes->responseType($partid);
                   4542: 			my %responseIds;
                   4543: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4544: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4545: 			}
                   4546: 			$responseType{$partid} = \%responseIds;
1.116     ng       4547: 		    }
1.148     albertel 4548: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4549: 
1.71      ng       4550: 		}
1.257     albertel 4551: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4552: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4553: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4554: 									$env{'request.course.id'},
1.71      ng       4555: 									'','.submission');
                   4556:  
                   4557: 	    }
1.103     albertel 4558: 	    if (&canmodify($usec)) {
1.585     bisitz   4559:             $studentTable.=&gradeBox_start();
1.103     albertel 4560: 		foreach my $partid (@{$parts}) {
                   4561: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4562: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4563: 		    $question++;
                   4564: 		}
1.585     bisitz   4565:             $studentTable.=&gradeBox_end();
1.196     albertel 4566: 		$prob++;
1.71      ng       4567: 	    }
                   4568: 	    $studentTable.='</td></tr>';
1.68      ng       4569: 
1.103     albertel 4570: 	}
1.68      ng       4571:         $curRes = $iterator->next();
                   4572:     }
                   4573: 
1.589     bisitz   4574:     $studentTable.=
                   4575:         '</table>'."\n".
                   4576:         '<input type="button" value="'.&mt('Save').'" '.
                   4577:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4578:         '</form>'."\n";
1.324     albertel 4579:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4580:     $request->print($studentTable);
                   4581: 
                   4582:     return '';
1.119     ng       4583: }
                   4584: 
                   4585: sub displaySubByDates {
1.148     albertel 4586:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4587:     my $isCODE=0;
1.335     albertel 4588:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4589:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4590:     my $studentTable=&Apache::loncommon::start_data_table().
                   4591: 	&Apache::loncommon::start_data_table_header_row().
                   4592: 	'<th>'.&mt('Date/Time').'</th>'.
                   4593: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4594: 	'<th>'.&mt('Submission').'</th>'.
                   4595: 	'<th>'.&mt('Status').'</th>'.
                   4596: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4597:     my ($version);
                   4598:     my %mark;
1.148     albertel 4599:     my %orders;
1.119     ng       4600:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4601:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4602: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4603:     }
1.335     albertel 4604: 
                   4605:     my $interaction;
1.525     raeburn  4606:     my $no_increment = 1;
1.119     ng       4607:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4608: 	my $timestamp = 
                   4609: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4610: 	if (exists($$record{$version.':resource.0.version'})) {
                   4611: 	    $interaction = $$record{$version.':resource.0.version'};
                   4612: 	}
                   4613: 
                   4614: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4615: 		             : "$version:resource");
1.467     albertel 4616: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4617: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4618: 	if ($isCODE) {
                   4619: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4620: 	}
1.119     ng       4621: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4622: 	my @displaySub = ();
                   4623: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4624:             my $hidden;
                   4625:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4626:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4627:                 $hidden = 1;
                   4628:             }
1.335     albertel 4629: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4630: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4631: 	    
1.122     ng       4632: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4633: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4634: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4635: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4636: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4637:                     
1.335     albertel 4638: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4639: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4640:                     $displaySub[0].='<span class="LC_nobreak"';
                   4641:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4642:                                    .' <span class="LC_internal_info">'
                   4643:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4644:                                    .'</span>'
                   4645:                                    .' <b>';
1.596     raeburn  4646:                     if ($hidden) {
                   4647:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4648:                     } else {
                   4649: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4650: 			    $displaySub[0].=&mt('Trial not counted');
                   4651: 		        } else {
                   4652: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4653: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4654: 		        }
                   4655: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4656:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4657: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4658: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4659: 			    $orders{$partid}->{$responseId}=
                   4660: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4661:                                            $no_increment);
                   4662: 		        }
                   4663: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4664: 		        $displaySub[0].='&nbsp; '.
                   4665: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4666:                     }
1.147     albertel 4667: 		}
                   4668: 	    }
1.335     albertel 4669: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4670: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4671: 				    $$record{"$where.$partid.checkedin"},
                   4672: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4673: 					'<br />';
1.335     albertel 4674: 	    }
                   4675: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4676: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4677: 		    lc($$record{"$where.$partid.award"}).' '.
                   4678: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4679: 		    '<br />';
                   4680: 	    }
1.335     albertel 4681: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4682: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4683: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4684: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4685: 		$displaySub[2].=
                   4686: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4687: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4688: 	    }
                   4689: 	}
                   4690: 	# needed because old essay regrader has not parts info
                   4691: 	if (exists $$record{"$version:resource.regrader"}) {
                   4692: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4693: 	}
                   4694: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4695: 	if ($displaySub[2]) {
1.467     albertel 4696: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4697: 	}
1.467     albertel 4698: 	$studentTable.='&nbsp;</td>'.
                   4699: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4700:     }
1.467     albertel 4701:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4702:     return $studentTable;
1.71      ng       4703: }
                   4704: 
                   4705: sub updateGradeByPage {
                   4706:     my ($request) = shift;
                   4707: 
1.257     albertel 4708:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4709:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4710:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4711:     my $pageTitle = $env{'form.page'};
1.103     albertel 4712:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4713:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4714:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4715:     if (!&canmodify($usec)) {
1.526     raeburn  4716: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4717: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4718: 	return;
                   4719:     }
1.398     albertel 4720:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4721:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4722: 	'</h3>'."\n";
1.70      ng       4723: 
1.68      ng       4724:     $request->print($result);
                   4725: 
1.582     raeburn  4726: 
1.132     bowersj2 4727:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4728:     unless (ref($navmap)) {
                   4729:         $request->print(&navmap_errormsg());
                   4730:         return;
                   4731:     }
1.257     albertel 4732:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4733:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4734:     if (!$map) {
1.527     raeburn  4735: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4736: 	my ($symb)=&get_symb($request);
                   4737: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4738: 	return; 
                   4739:     }
1.71      ng       4740:     my $iterator = $navmap->getIterator($map->map_start(),
                   4741: 					$map->map_finish());
1.70      ng       4742: 
1.484     albertel 4743:     my $studentTable=
                   4744: 	&Apache::loncommon::start_data_table().
                   4745: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4746: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4747: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4748: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4749: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4750: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4751: 
                   4752:     $iterator->next(); # skip the first BEGIN_MAP
                   4753:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4754:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4755:     while ($depth > 0) {
1.71      ng       4756:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4757:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4758: 
1.385     albertel 4759:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4760: 	    my $parts = $curRes->parts();
1.71      ng       4761:             my $title = $curRes->compTitle();
                   4762: 	    my $symbx = $curRes->symb();
1.484     albertel 4763: 	    $studentTable.=
                   4764: 		&Apache::loncommon::start_data_table_row().
                   4765: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4766: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4767:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4768: 		.')').'</td>';
1.71      ng       4769: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4770: 
                   4771: 	    my %newrecord=();
                   4772: 	    my @displayPts=();
1.269     raeburn  4773:             my %aggregate = ();
                   4774:             my $aggregateflag = 0;
1.71      ng       4775: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4776: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4777: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4778: 
1.257     albertel 4779: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4780: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4781: 		my $partial = $newpts/$wgt;
                   4782: 		my $score;
                   4783: 		if ($partial > 0) {
                   4784: 		    $score = 'correct_by_override';
1.125     ng       4785: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4786: 		    $score = 'incorrect_by_override';
                   4787: 		}
1.257     albertel 4788: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4789: 		if ($dropMenu eq 'excused') {
1.71      ng       4790: 		    $partial = '';
                   4791: 		    $score = 'excused';
1.125     ng       4792: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4793: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4794: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4795: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4796: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4797: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4798: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4799: 		    $changeflag++;
                   4800: 		    $newpts = '';
1.269     raeburn  4801:                     
                   4802:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4803:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4804:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4805:                     if ($aggtries > 0) {
                   4806:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4807:                         $aggregateflag = 1;
                   4808:                     }
1.71      ng       4809: 		}
1.324     albertel 4810: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4811: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4812: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4813: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4814: 		    '&nbsp;<br />';
1.526     raeburn  4815: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4816: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4817: 		    '&nbsp;<br />';
1.71      ng       4818: 		$question++;
1.380     albertel 4819: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4820: 
1.71      ng       4821: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4822: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4823: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4824: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4825: 
                   4826: 		$changeflag++;
                   4827: 	    }
                   4828: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4829: 		my %record = 
                   4830: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4831: 					     $udom,$uname);
                   4832: 
                   4833: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4834: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4835: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4836: 		    $newrecord{'resource.CODE'} = '';
                   4837: 		}
1.257     albertel 4838: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4839: 					$udom,$uname);
1.382     albertel 4840: 		%record = &Apache::lonnet::restore($symbx,
                   4841: 						   $env{'request.course.id'},
                   4842: 						   $udom,$uname);
1.380     albertel 4843: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4844: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4845: 	    }
1.380     albertel 4846: 	    
1.269     raeburn  4847:             if ($aggregateflag) {
                   4848:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4849:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4850:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4851:             }
1.125     ng       4852: 
1.71      ng       4853: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4854: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4855: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4856: 
1.196     albertel 4857: 	    $prob++;
1.68      ng       4858: 	}
1.71      ng       4859:         $curRes = $iterator->next();
1.68      ng       4860:     }
1.98      albertel 4861: 
1.484     albertel 4862:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4863:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4864:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4865: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4866: 		  $changeflag));
1.76      ng       4867:     $request->print($grademsg.$studentTable);
1.68      ng       4868: 
1.70      ng       4869:     return '';
                   4870: }
                   4871: 
1.72      ng       4872: #-------- end of section for handling grading by page/sequence ---------
                   4873: #
                   4874: #-------------------------------------------------------------------
                   4875: 
1.581     www      4876: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4877: #
                   4878: #------ start of section for handling grading by page/sequence ---------
                   4879: 
1.423     albertel 4880: =pod
                   4881: 
                   4882: =head1 Bubble sheet grading routines
                   4883: 
1.424     albertel 4884:   For this documentation:
                   4885: 
                   4886:    'scanline' refers to the full line of characters
                   4887:    from the file that we are parsing that represents one entire sheet
                   4888: 
                   4889:    'bubble line' refers to the data
                   4890:    representing the line of bubbles that are on the physical bubble sheet
                   4891: 
                   4892: 
                   4893: The overall process is that a scanned in bubble sheet data is uploaded
                   4894: into a course. When a user wants to grade, they select a
                   4895: sequence/folder of resources, a file of bubble sheet info, and pick
                   4896: one of the predefined configurations for what each scanline looks
                   4897: like.
                   4898: 
                   4899: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4900: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4901: because too light bubbling), 'double bubble' (each bubble line should
                   4902: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4903: invalid student/employee ID
1.424     albertel 4904: 
                   4905: If the CODE option is used that determines the randomization of the
1.556     weissno  4906: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4907: username:domain.
                   4908: 
                   4909: During the validation phase the instructor can choose to skip scanlines. 
                   4910: 
1.435     foxr     4911: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4912: 
                   4913:   scantron_original_filename (unmodified original file)
                   4914:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4915:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4916: 
                   4917: Also there is a separate hash nohist_scantrondata that contains extra
                   4918: correction information that isn't representable in the bubble sheet
                   4919: file (see &scantron_getfile() for more information)
                   4920: 
                   4921: After all scanlines are either valid, marked as valid or skipped, then
                   4922: foreach line foreach problem in the picked sequence, an ssi request is
                   4923: made that simulates a user submitting their selected letter(s) against
                   4924: the homework problem.
1.423     albertel 4925: 
                   4926: =over 4
                   4927: 
                   4928: 
                   4929: 
                   4930: =item defaultFormData
                   4931: 
                   4932:   Returns html hidden inputs used to hold context/default values.
                   4933: 
                   4934:  Arguments:
                   4935:   $symb - $symb of the current resource 
                   4936: 
                   4937: =cut
1.422     foxr     4938: 
1.81      albertel 4939: sub defaultFormData {
1.324     albertel 4940:     my ($symb)=@_;
1.447     foxr     4941:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4942:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4943:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4944: }
                   4945: 
1.447     foxr     4946: 
1.423     albertel 4947: =pod 
                   4948: 
                   4949: =item getSequenceDropDown
                   4950: 
                   4951:    Return html dropdown of possible sequences to grade
                   4952:  
                   4953:  Arguments:
1.582     raeburn  4954:    $symb - $symb of the current resource
                   4955:    $map_error - ref to scalar which will container error if
                   4956:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4957: 
                   4958: =cut
1.422     foxr     4959: 
1.75      albertel 4960: sub getSequenceDropDown {
1.582     raeburn  4961:     my ($symb,$map_error)=@_;
1.75      albertel 4962:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4963:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4964:     if (ref($map_error)) {
                   4965:         return if ($$map_error);
                   4966:     }
1.137     albertel 4967:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4968:     my $ctr=0;
                   4969:     foreach (@$titles) {
                   4970: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4971: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4972: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4973: 	    '>'.$showtitle.'</option>'."\n";
                   4974: 	$ctr++;
                   4975:     }
                   4976:     $result.= '</select>';
                   4977:     return $result;
                   4978: }
                   4979: 
1.495     albertel 4980: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4981:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4982: 
                   4983: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4984: 
1.509     raeburn  4985: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4986:                                    # matchresponse or rankresponse, where 
                   4987:                                    # an individual response can have multiple 
                   4988:                                    # lines
1.503     raeburn  4989: 
                   4990: my %responsetype_per_response;     # responsetype for each response
                   4991: 
1.495     albertel 4992: # Save and restore the bubble lines array to the form env.
                   4993: 
                   4994: 
                   4995: sub save_bubble_lines {
                   4996:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4997: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4998: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4999: 	    $first_bubble_line{$line};
1.503     raeburn  5000:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5001:             $subdivided_bubble_lines{$line};
                   5002:         $env{"form.scantron.responsetype.$line"} =
                   5003:             $responsetype_per_response{$line};
1.495     albertel 5004:     }
                   5005: }
                   5006: 
                   5007: 
                   5008: sub restore_bubble_lines {
                   5009:     my $line = 0;
                   5010:     %bubble_lines_per_response = ();
                   5011:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5012: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5013: 	$bubble_lines_per_response{$line} = $value;
                   5014: 	$first_bubble_line{$line}  =
                   5015: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5016:         $subdivided_bubble_lines{$line} =
                   5017:             $env{"form.scantron.sub_bubblelines.$line"};
                   5018:         $responsetype_per_response{$line} =
                   5019:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 5020: 	$line++;
                   5021:     }
                   5022: }
                   5023: 
                   5024: #  Given the parsed scanline, get the response for 
                   5025: #  'answer' number n:
                   5026: 
                   5027: sub get_response_bubbles {
                   5028:     my ($parsed_line, $response)  = @_;
                   5029: 
                   5030:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   5031:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   5032:     
                   5033:     my $selected = "";
                   5034: 
                   5035:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   5036: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   5037: 	$bubble_line++;
                   5038:     }
                   5039:     return $selected;
                   5040: }
1.423     albertel 5041: 
                   5042: =pod 
                   5043: 
                   5044: =item scantron_filenames
                   5045: 
                   5046:    Returns a list of the scantron files in the current course 
                   5047: 
                   5048: =cut
1.422     foxr     5049: 
1.202     albertel 5050: sub scantron_filenames {
1.257     albertel 5051:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5052:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5053:     my $getpropath = 1;
1.157     albertel 5054:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  5055:                                        $getpropath);
1.202     albertel 5056:     my @possiblenames;
1.201     albertel 5057:     foreach my $filename (sort(@files)) {
1.157     albertel 5058: 	($filename)=split(/&/,$filename);
                   5059: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5060: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5061: 	push(@possiblenames,$filename);
                   5062:     }
                   5063:     return @possiblenames;
                   5064: }
                   5065: 
1.423     albertel 5066: =pod 
                   5067: 
                   5068: =item scantron_uploads
                   5069: 
                   5070:    Returns  html drop-down list of scantron files in current course.
                   5071: 
                   5072:  Arguments:
                   5073:    $file2grade - filename to set as selected in the dropdown
                   5074: 
                   5075: =cut
1.422     foxr     5076: 
1.202     albertel 5077: sub scantron_uploads {
1.209     ng       5078:     my ($file2grade) = @_;
1.202     albertel 5079:     my $result=	'<select name="scantron_selectfile">';
                   5080:     $result.="<option></option>";
                   5081:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5082: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5083:     }
                   5084:     $result.="</select>";
                   5085:     return $result;
                   5086: }
                   5087: 
1.423     albertel 5088: =pod 
                   5089: 
                   5090: =item scantron_scantab
                   5091: 
                   5092:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5093:   file.
                   5094: 
                   5095: =cut
1.422     foxr     5096: 
1.82      albertel 5097: sub scantron_scantab {
                   5098:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5099:     $result.='<option></option>'."\n";
1.518     raeburn  5100:     my @lines = &get_scantronformat_file();
                   5101:     if (@lines > 0) {
                   5102:         foreach my $line (@lines) {
                   5103:             next if (($line =~ /^\#/) || ($line eq ''));
                   5104: 	    my ($name,$descrip)=split(/:/,$line);
                   5105: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5106:         }
1.82      albertel 5107:     }
                   5108:     $result.='</select>'."\n";
1.518     raeburn  5109:     return $result;
                   5110: }
                   5111: 
                   5112: =pod
                   5113: 
                   5114: =item get_scantronformat_file
                   5115: 
                   5116:   Returns an array containing lines from the scantron format file for
                   5117:   the domain of the course.
                   5118: 
                   5119:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5120:   lines are from this file.
                   5121: 
                   5122:   Otherwise, if a default.tab has been published in RES space by the 
                   5123:   domainconfig user, lines are from this file.
                   5124: 
                   5125:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5126:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5127: 
1.518     raeburn  5128: =cut
                   5129: 
                   5130: sub get_scantronformat_file {
                   5131:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5132:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5133:     my $gottab = 0;
                   5134:     my @lines;
                   5135:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5136:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5137:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5138:             if ($formatfile ne '-1') {
                   5139:                 @lines = split("\n",$formatfile,-1);
                   5140:                 $gottab = 1;
                   5141:             }
                   5142:         }
                   5143:     }
                   5144:     if (!$gottab) {
                   5145:         my $confname = $cdom.'-domainconfig';
                   5146:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5147:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5148:         if ($formatfile ne '-1') {
                   5149:             @lines = split("\n",$formatfile,-1);
                   5150:             $gottab = 1;
                   5151:         }
                   5152:     }
                   5153:     if (!$gottab) {
1.519     raeburn  5154:         my @domains = &Apache::lonnet::current_machine_domains();
                   5155:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5156:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5157:             @lines = <$fh>;
                   5158:             close($fh);
                   5159:         } else {
                   5160:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5161:             @lines = <$fh>;
                   5162:             close($fh);
                   5163:         }
1.518     raeburn  5164:     }
                   5165:     return @lines;
1.82      albertel 5166: }
                   5167: 
1.423     albertel 5168: =pod 
                   5169: 
                   5170: =item scantron_CODElist
                   5171: 
                   5172:   Returns html drop down of the saved CODE lists from current course,
                   5173:   generated from earlier printings.
                   5174: 
                   5175: =cut
1.422     foxr     5176: 
1.186     albertel 5177: sub scantron_CODElist {
1.257     albertel 5178:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5179:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5180:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5181:     my $namechoice='<option></option>';
1.225     albertel 5182:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5183: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5184: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5185: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5186:     }
                   5187:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5188:     return $namechoice;
                   5189: }
                   5190: 
1.423     albertel 5191: =pod 
                   5192: 
                   5193: =item scantron_CODEunique
                   5194: 
                   5195:   Returns the html for "Each CODE to be used once" radio.
                   5196: 
                   5197: =cut
1.422     foxr     5198: 
1.186     albertel 5199: sub scantron_CODEunique {
1.532     bisitz   5200:     my $result='<span class="LC_nobreak">
1.272     albertel 5201:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5202:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5203:                 </span>
1.532     bisitz   5204:                 <span class="LC_nobreak">
1.272     albertel 5205:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5206:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5207:                 </span>';
1.186     albertel 5208:     return $result;
                   5209: }
1.423     albertel 5210: 
                   5211: =pod 
                   5212: 
                   5213: =item scantron_selectphase
                   5214: 
                   5215:   Generates the initial screen to start the bubble sheet process.
                   5216:   Allows for - starting a grading run.
1.424     albertel 5217:              - downloading existing scan data (original, corrected
1.423     albertel 5218:                                                 or skipped info)
                   5219: 
                   5220:              - uploading new scan data
                   5221: 
                   5222:  Arguments:
                   5223:   $r          - The Apache request object
                   5224:   $file2grade - name of the file that contain the scanned data to score
                   5225: 
                   5226: =cut
1.186     albertel 5227: 
1.75      albertel 5228: sub scantron_selectphase {
1.209     ng       5229:     my ($r,$file2grade) = @_;
1.324     albertel 5230:     my ($symb)=&get_symb($r);
1.75      albertel 5231:     if (!$symb) {return '';}
1.582     raeburn  5232:     my $map_error;
                   5233:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5234:     if ($map_error) {
                   5235:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5236:         return;
                   5237:     }
1.324     albertel 5238:     my $default_form_data=&defaultFormData($symb);
                   5239:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5240:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5241:     my $format_selector=&scantron_scantab();
1.186     albertel 5242:     my $CODE_selector=&scantron_CODElist();
                   5243:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5244:     my $result;
1.422     foxr     5245: 
1.513     foxr     5246:     $ssi_error = 0;
                   5247: 
1.422     foxr     5248:     # Chunk of form to prompt for a file to grade and how:
                   5249: 
1.489     albertel 5250:     $result.= '
                   5251:     <br />
                   5252:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5253:     <input type="hidden" name="command" value="scantron_warning" />
                   5254:     '.$default_form_data.'
                   5255:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5256:        '.&Apache::loncommon::start_data_table_header_row().'
                   5257:             <th colspan="2">
1.492     albertel 5258:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5259:             </th>
                   5260:        '.&Apache::loncommon::end_data_table_header_row().'
                   5261:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5262:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5263:        '.&Apache::loncommon::end_data_table_row().'
                   5264:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5265:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5266:        '.&Apache::loncommon::end_data_table_row().'
                   5267:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5268:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5269:        '.&Apache::loncommon::end_data_table_row().'
                   5270:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5271:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5272:        '.&Apache::loncommon::end_data_table_row().'
                   5273:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5274:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5275:        '.&Apache::loncommon::end_data_table_row().'
                   5276:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5277: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5278:             <td>
1.492     albertel 5279: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5280:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5281:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5282: 	    </td>
1.489     albertel 5283:        '.&Apache::loncommon::end_data_table_row().'
                   5284:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5285:             <td colspan="2">
1.572     www      5286:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5287:             </td>
1.489     albertel 5288:        '.&Apache::loncommon::end_data_table_row().'
                   5289:     '.&Apache::loncommon::end_data_table().'
                   5290:     </form>
                   5291: ';
1.162     albertel 5292:    
                   5293:     $r->print($result);
                   5294: 
1.257     albertel 5295:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5296:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5297: 
1.422     foxr     5298: 	# Chunk of form to prompt for a scantron file upload.
                   5299: 
1.489     albertel 5300:         $r->print('
                   5301:     <br />
                   5302:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5303:        '.&Apache::loncommon::start_data_table_header_row().'
                   5304:             <th>
1.572     www      5305:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
1.489     albertel 5306:             </th>
                   5307:        '.&Apache::loncommon::end_data_table_header_row().'
                   5308:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5309:             <td>
1.489     albertel 5310: ');
1.324     albertel 5311:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5312:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5313:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.597     wenzelju 5314:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.174     albertel 5315:     function checkUpload(formname) {
                   5316: 	if (formname.upfile.value == "") {
1.492     albertel 5317: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5318: 	    return false;
                   5319: 	}
                   5320: 	formname.submit();
1.597     wenzelju 5321:     }'));
                   5322:     $r->print('
1.492     albertel 5323:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5324:                 '.$default_form_data.'
                   5325:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5326:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5327:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5328:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5329:                 <br />
1.589     bisitz   5330:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.174     albertel 5331:               </form>
1.492     albertel 5332: ');
1.162     albertel 5333: 
1.489     albertel 5334:         $r->print('
1.162     albertel 5335:             </td>
1.489     albertel 5336:        '.&Apache::loncommon::end_data_table_row().'
                   5337:        '.&Apache::loncommon::end_data_table().'
                   5338: ');
1.162     albertel 5339:     }
1.422     foxr     5340: 
                   5341:     # Chunk of the form that prompts to view a scoring office file,
                   5342:     # corrected file, skipped records in a file.
                   5343: 
1.489     albertel 5344:     $r->print('
                   5345:    <br />
                   5346:    <form action="/adm/grades" name="scantron_download">
                   5347:      '.$default_form_data.'
                   5348:      <input type="hidden" name="command" value="scantron_download" />
                   5349:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5350:        '.&Apache::loncommon::start_data_table_header_row().'
                   5351:               <th>
1.492     albertel 5352:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5353:               </th>
                   5354:        '.&Apache::loncommon::end_data_table_header_row().'
                   5355:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5356:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5357:                 <br />
1.492     albertel 5358:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5359:        '.&Apache::loncommon::end_data_table_row().'
                   5360:      '.&Apache::loncommon::end_data_table().'
                   5361:    </form>
                   5362:    <br />
                   5363: ');
1.162     albertel 5364: 
1.457     banghart 5365:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5366: 
1.528     raeburn  5367:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5368:              $default_form_data."\n".
                   5369:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5370:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5371:              '<th colspan="2">
1.572     www      5372:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5373:              '</th>'."\n".
                   5374:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5375:               &Apache::loncommon::start_data_table_row()."\n".
                   5376:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5377:               '<td> '.$sequence_selector.' </td>'.
                   5378:               &Apache::loncommon::end_data_table_row()."\n".
                   5379:               &Apache::loncommon::start_data_table_row()."\n".
                   5380:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5381:               '<td> '.$file_selector.' </td>'."\n".
                   5382:               &Apache::loncommon::end_data_table_row()."\n".
                   5383:               &Apache::loncommon::start_data_table_row()."\n".
                   5384:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5385:               '<td> '.$format_selector.' </td>'."\n".
                   5386:               &Apache::loncommon::end_data_table_row()."\n".
                   5387:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5388:               '<td> '.&mt('Options').' </td>'."\n".
                   5389:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5390:               &Apache::loncommon::end_data_table_row()."\n".
                   5391:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5392:               '<td colspan="2">'."\n".
                   5393:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5394:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5395:               '</td>'."\n".
                   5396:               &Apache::loncommon::end_data_table_row()."\n".
                   5397:               &Apache::loncommon::end_data_table()."\n".
                   5398:               '</form><br />');
1.457     banghart 5399:     $r->print($grading_menu_button);
1.523     raeburn  5400:     return;
1.75      albertel 5401: }
                   5402: 
1.423     albertel 5403: =pod
                   5404: 
                   5405: =item get_scantron_config
                   5406: 
                   5407:    Parse and return the scantron configuration line selected as a
                   5408:    hash of configuration file fields.
                   5409: 
                   5410:  Arguments:
                   5411:     which - the name of the configuration to parse from the file.
                   5412: 
                   5413: 
                   5414:  Returns:
                   5415:             If the named configuration is not in the file, an empty
                   5416:             hash is returned.
                   5417:     a hash with the fields
                   5418:       name         - internal name for the this configuration setup
                   5419:       description  - text to display to operator that describes this config
                   5420:       CODElocation - if 0 or the string 'none'
                   5421:                           - no CODE exists for this config
                   5422:                      if -1 || the string 'letter'
                   5423:                           - a CODE exists for this config and is
                   5424:                             a string of letters
                   5425:                      Unsupported value (but planned for future support)
                   5426:                           if a positive integer
                   5427:                                - The CODE exists as the first n items from
                   5428:                                  the question section of the form
                   5429:                           if the string 'number'
                   5430:                                - The CODE exists for this config and is
                   5431:                                  a string of numbers
                   5432:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5433:                      the CODE starts
                   5434:       CODElength  - length of the CODE
1.573     bisitz   5435:       IDstart     - column where the student/employee ID starts
1.556     weissno  5436:       IDlength    - length of the student/employee ID info
1.423     albertel 5437:       Qstart      - column where the information from the bubbled
                   5438:                     'questions' start
                   5439:       Qlength     - number of columns comprising a single bubble line from
                   5440:                     the sheet. (usually either 1 or 10)
1.424     albertel 5441:       Qon         - either a single character representing the character used
1.423     albertel 5442:                     to signal a bubble was chosen in the positional setup, or
                   5443:                     the string 'letter' if the letter of the chosen bubble is
                   5444:                     in the final, or 'number' if a number representing the
                   5445:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5446:       Qoff        - the character used to represent that a bubble was
                   5447:                     left blank
1.423     albertel 5448:       PaperID     - if the scanning process generates a unique number for each
                   5449:                     sheet scanned the column that this ID number starts in
                   5450:       PaperIDlength - number of columns that comprise the unique ID number
                   5451:                       for the sheet of paper
1.424     albertel 5452:       FirstName   - column that the first name starts in
1.423     albertel 5453:       FirstNameLength - number of columns that the first name spans
                   5454:  
                   5455:       LastName    - column that the last name starts in
                   5456:       LastNameLength - number of columns that the last name spans
                   5457: 
                   5458: =cut
1.422     foxr     5459: 
1.82      albertel 5460: sub get_scantron_config {
                   5461:     my ($which) = @_;
1.518     raeburn  5462:     my @lines = &get_scantronformat_file();
1.82      albertel 5463:     my %config;
1.157     albertel 5464:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5465:     foreach my $line (@lines) {
1.82      albertel 5466: 	my ($name,$descrip)=split(/:/,$line);
                   5467: 	if ($name ne $which ) { next; }
                   5468: 	chomp($line);
                   5469: 	my @config=split(/:/,$line);
                   5470: 	$config{'name'}=$config[0];
                   5471: 	$config{'description'}=$config[1];
                   5472: 	$config{'CODElocation'}=$config[2];
                   5473: 	$config{'CODEstart'}=$config[3];
                   5474: 	$config{'CODElength'}=$config[4];
                   5475: 	$config{'IDstart'}=$config[5];
                   5476: 	$config{'IDlength'}=$config[6];
                   5477: 	$config{'Qstart'}=$config[7];
1.497     foxr     5478:  	$config{'Qlength'}=$config[8];
1.82      albertel 5479: 	$config{'Qoff'}=$config[9];
                   5480: 	$config{'Qon'}=$config[10];
1.157     albertel 5481: 	$config{'PaperID'}=$config[11];
                   5482: 	$config{'PaperIDlength'}=$config[12];
                   5483: 	$config{'FirstName'}=$config[13];
                   5484: 	$config{'FirstNamelength'}=$config[14];
                   5485: 	$config{'LastName'}=$config[15];
                   5486: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5487: 	last;
                   5488:     }
                   5489:     return %config;
                   5490: }
                   5491: 
1.423     albertel 5492: =pod 
                   5493: 
                   5494: =item username_to_idmap
                   5495: 
1.556     weissno  5496:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5497:     student username:domain.
                   5498: 
                   5499:   Arguments:
                   5500: 
                   5501:     $classlist - reference to the class list hash. This is a hash
                   5502:                  keyed by student name:domain  whose elements are references
1.424     albertel 5503:                  to arrays containing various chunks of information
1.423     albertel 5504:                  about the student. (See loncoursedata for more info).
                   5505: 
                   5506:   Returns
                   5507:     %idmap - the constructed hash
                   5508: 
                   5509: =cut
                   5510: 
1.82      albertel 5511: sub username_to_idmap {
                   5512:     my ($classlist)= @_;
                   5513:     my %idmap;
                   5514:     foreach my $student (keys(%$classlist)) {
                   5515: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5516: 	    $student;
                   5517:     }
                   5518:     return %idmap;
                   5519: }
1.423     albertel 5520: 
                   5521: =pod
                   5522: 
1.424     albertel 5523: =item scantron_fixup_scanline
1.423     albertel 5524: 
                   5525:    Process a requested correction to a scanline.
                   5526: 
                   5527:   Arguments:
                   5528:     $scantron_config   - hash from &get_scantron_config()
                   5529:     $scan_data         - hash of correction information 
                   5530:                           (see &scantron_getfile())
                   5531:     $line              - existing scanline
                   5532:     $whichline         - line number of the passed in scanline
                   5533:     $field             - type of change to process 
                   5534:                          (either 
1.573     bisitz   5535:                           'ID'     -> correct the student/employee ID
1.423     albertel 5536:                           'CODE'   -> correct the CODE
                   5537:                           'answer' -> fixup the submitted answers)
                   5538:     
                   5539:    $args               - hash of additional info,
                   5540:                           - 'ID' 
                   5541:                                'newid' -> studentID to use in replacement
1.424     albertel 5542:                                           of existing one
1.423     albertel 5543:                           - 'CODE' 
                   5544:                                'CODE_ignore_dup' - set to true if duplicates
                   5545:                                                    should be ignored.
                   5546: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5547:                                         if the existing unfound code should
1.423     albertel 5548:                                         be used as is
                   5549:                           - 'answer'
                   5550:                                'response' - new answer or 'none' if blank
                   5551:                                'question' - the bubble line to change
1.503     raeburn  5552:                                'questionnum' - the question identifier,
                   5553:                                                may include subquestion. 
1.423     albertel 5554: 
                   5555:   Returns:
                   5556:     $line - the modified scanline
                   5557: 
                   5558:   Side effects: 
                   5559:     $scan_data - may be updated
                   5560: 
                   5561: =cut
                   5562: 
1.82      albertel 5563: 
1.157     albertel 5564: sub scantron_fixup_scanline {
                   5565:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5566:     if ($field eq 'ID') {
                   5567: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5568: 	    return ($line,1,'New value too large');
1.157     albertel 5569: 	}
                   5570: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5571: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5572: 				     $args->{'newid'});
                   5573: 	}
                   5574: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5575: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5576: 	if ($args->{'newid'}=~/^\s*$/) {
                   5577: 	    &scan_data($scan_data,"$whichline.user",
                   5578: 		       $args->{'username'}.':'.$args->{'domain'});
                   5579: 	}
1.186     albertel 5580:     } elsif ($field eq 'CODE') {
1.192     albertel 5581: 	if ($args->{'CODE_ignore_dup'}) {
                   5582: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5583: 	}
                   5584: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5585: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5586: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5587: 		return ($line,1,'New CODE value too large');
                   5588: 	    }
                   5589: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5590: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5591: 	    }
                   5592: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5593: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5594: 	}
1.157     albertel 5595:     } elsif ($field eq 'answer') {
1.497     foxr     5596: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5597: 	my $off=$scantron_config->{'Qoff'};
                   5598: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5599: 	my $answer=${off}x$length;
                   5600: 	if ($args->{'response'} eq 'none') {
                   5601: 	    &scan_data($scan_data,
1.503     raeburn  5602: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5603: 	} else {
                   5604: 	    if ($on eq 'letter') {
                   5605: 		my @alphabet=('A'..'Z');
                   5606: 		$answer=$alphabet[$args->{'response'}];
                   5607: 	    } elsif ($on eq 'number') {
                   5608: 		$answer=$args->{'response'}+1;
                   5609: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5610: 	    } else {
1.497     foxr     5611: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5612: 	    }
1.497     foxr     5613: 	    &scan_data($scan_data,
1.503     raeburn  5614: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5615: 	}
1.497     foxr     5616: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5617: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5618:     }
                   5619:     return $line;
                   5620: }
1.423     albertel 5621: 
                   5622: =pod
                   5623: 
                   5624: =item scan_data
                   5625: 
                   5626:     Edit or look up  an item in the scan_data hash.
                   5627: 
                   5628:   Arguments:
                   5629:     $scan_data  - The hash (see scantron_getfile)
                   5630:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5631:                   scantronfilename_key).
1.423     albertel 5632:     $data        - New value of the hash entry.
                   5633:     $delete      - If true, the entry is removed from the hash.
                   5634: 
                   5635:   Returns:
                   5636:     The new value of the hash table field (undefined if deleted).
                   5637: 
                   5638: =cut
                   5639: 
                   5640: 
1.157     albertel 5641: sub scan_data {
                   5642:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5643:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5644:     if (defined($value)) {
                   5645: 	$scan_data->{$filename.'_'.$key} = $value;
                   5646:     }
                   5647:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5648:     return $scan_data->{$filename.'_'.$key};
                   5649: }
1.423     albertel 5650: 
1.495     albertel 5651: # ----- These first few routines are general use routines.----
                   5652: 
                   5653: # Return the number of occurences of a pattern in a string.
                   5654: 
                   5655: sub occurence_count {
                   5656:     my ($string, $pattern) = @_;
                   5657: 
                   5658:     my @matches = ($string =~ /$pattern/g);
                   5659: 
                   5660:     return scalar(@matches);
                   5661: }
                   5662: 
                   5663: 
                   5664: # Take a string known to have digits and convert all the
                   5665: # digits into letters in the range J,A..I.
                   5666: 
                   5667: sub digits_to_letters {
                   5668:     my ($input) = @_;
                   5669: 
                   5670:     my @alphabet = ('J', 'A'..'I');
                   5671: 
                   5672:     my @input    = split(//, $input);
                   5673:     my $output ='';
                   5674:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5675: 	if ($input[$i] =~ /\d/) {
                   5676: 	    $output .= $alphabet[$input[$i]];
                   5677: 	} else {
                   5678: 	    $output .= $input[$i];
                   5679: 	}
                   5680:     }
                   5681:     return $output;
                   5682: }
                   5683: 
1.423     albertel 5684: =pod 
                   5685: 
                   5686: =item scantron_parse_scanline
                   5687: 
                   5688:   Decodes a scanline from the selected scantron file
                   5689: 
                   5690:  Arguments:
                   5691:     line             - The text of the scantron file line to process
                   5692:     whichline        - Line number
                   5693:     scantron_config  - Hash describing the format of the scantron lines.
                   5694:     scan_data        - Hash of extra information about the scanline
                   5695:                        (see scantron_getfile for more information)
                   5696:     just_header      - True if should not process question answers but only
                   5697:                        the stuff to the left of the answers.
                   5698:  Returns:
                   5699:    Hash containing the result of parsing the scanline
                   5700: 
                   5701:    Keys are all proceeded by the string 'scantron.'
                   5702: 
                   5703:        CODE    - the CODE in use for this scanline
                   5704:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5705:                  by the operator
                   5706:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5707:                             CODEs were selected, but the usage has been
                   5708:                             forced by the operator
1.556     weissno  5709:        ID  - student/employee ID
1.423     albertel 5710:        PaperID - if used, the ID number printed on the sheet when the 
                   5711:                  paper was scanned
                   5712:        FirstName - first name from the sheet
                   5713:        LastName  - last name from the sheet
                   5714: 
                   5715:      if just_header was not true these key may also exist
                   5716: 
1.447     foxr     5717:        missingerror - a list of bubble ranges that are considered to be answers
                   5718:                       to a single question that don't have any bubbles filled in.
                   5719:                       Of the form questionnumber:firstbubblenumber:count.
                   5720:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5721:                       to a single question that have more than one bubble filled in.
                   5722:                       Of the form questionnumber::firstbubblenumber:count
                   5723:    
                   5724:                 In the above, count is the number of bubble responses in the
                   5725:                 input line needed to represent the possible answers to the question.
                   5726:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5727:                 per line would have count = 2.
                   5728: 
1.423     albertel 5729:        maxquest     - the number of the last bubble line that was parsed
                   5730: 
                   5731:        (<number> starts at 1)
                   5732:        <number>.answer - zero or more letters representing the selected
                   5733:                          letters from the scanline for the bubble line 
                   5734:                          <number>.
                   5735:                          if blank there was either no bubble or there where
                   5736:                          multiple bubbles, (consult the keys missingerror and
                   5737:                          doubleerror if this is an error condition)
                   5738: 
                   5739: =cut
                   5740: 
1.82      albertel 5741: sub scantron_parse_scanline {
1.423     albertel 5742:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5743: 
1.82      albertel 5744:     my %record;
1.550     raeburn  5745:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5746:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5747:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5748:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5749: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5750: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5751: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5752: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5753: 	    $record{'scantron.CODE'}=substr($data,
                   5754: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5755: 					    $$scantron_config{'CODElength'});
1.191     albertel 5756: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5757: 		$record{'scantron.useCODE'}=1;
                   5758: 	    }
1.192     albertel 5759: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5760: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5761: 	    }
1.82      albertel 5762: 	} else {
                   5763: 	    #FIXME interpret first N questions
                   5764: 	}
                   5765:     }
1.83      albertel 5766:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5767: 				  $$scantron_config{'IDlength'});
1.157     albertel 5768:     $record{'scantron.PaperID'}=
                   5769: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5770: 	       $$scantron_config{'PaperIDlength'});
                   5771:     $record{'scantron.FirstName'}=
                   5772: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5773: 	       $$scantron_config{'FirstNamelength'});
                   5774:     $record{'scantron.LastName'}=
                   5775: 	substr($data,$$scantron_config{'LastName'}-1,
                   5776: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5777:     if ($just_header) { return \%record; }
1.194     albertel 5778: 
1.82      albertel 5779:     my @alphabet=('A'..'Z');
                   5780:     my $questnum=0;
1.447     foxr     5781:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5782: 
1.470     foxr     5783:     chomp($questions);		# Get rid of any trailing \n.
                   5784:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5785:     while (length($questions)) {
1.447     foxr     5786: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5787:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5788:                              || 1;
                   5789:         $questnum++;
                   5790:         my $quest_id = $questnum;
                   5791:         my $currentquest = substr($questions,0,$answer_length);
                   5792:         $questions       = substr($questions,$answer_length);
                   5793:         if (length($currentquest) < $answer_length) { next; }
                   5794: 
                   5795:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5796:             my $subquestnum = 1;
                   5797:             my $subquestions = $currentquest;
                   5798:             my @subanswers_needed = 
                   5799:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5800:             foreach my $subans (@subanswers_needed) {
                   5801:                 my $subans_length =
                   5802:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5803:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5804:                 $subquestions   = substr($subquestions,$subans_length);
                   5805:                 $quest_id = "$questnum.$subquestnum";
                   5806:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5807:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5808:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5809:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5810:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5811:                 } else {
                   5812:                     $ansnum = &scantron_validator_positional($ansnum,
                   5813:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5814:                 }
                   5815:                 $subquestnum ++;
                   5816:             }
                   5817:         } else {
                   5818:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5819:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5820:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5821:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5822:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5823:             } else {
                   5824:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5825:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5826:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5827:             }
                   5828:         }
                   5829:     }
                   5830:     $record{'scantron.maxquest'}=$questnum;
                   5831:     return \%record;
                   5832: }
1.447     foxr     5833: 
1.503     raeburn  5834: sub scantron_validator_lettnum {
                   5835:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5836:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5837: 
                   5838:     # Qon 'letter' implies for each slot in currquest we have:
                   5839:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5840:     #    about anything else (esp. a value of Qoff) for missing
                   5841:     #    bubbles.
                   5842:     #
                   5843:     # Qon 'number' implies each slot gives a digit that indexes the
                   5844:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5845:     #    and * or ? for double bubbles on a single line.
                   5846:     #
1.447     foxr     5847: 
1.503     raeburn  5848:     my $matchon;
                   5849:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5850:         $matchon = '[A-Z]';
                   5851:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5852:         $matchon = '\d';
                   5853:     }
                   5854:     my $occurrences = 0;
                   5855:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5856:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5857:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5858:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5859:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5860:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5861:         my @singlelines = split('',$currquest);
                   5862:         foreach my $entry (@singlelines) {
                   5863:             $occurrences = &occurence_count($entry,$matchon);
                   5864:             if ($occurrences > 1) {
                   5865:                 last;
                   5866:             }
                   5867:         } 
                   5868:     } else {
                   5869:         $occurrences = &occurence_count($currquest,$matchon); 
                   5870:     }
                   5871:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5872:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5873:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5874:             my $bubble = substr($currquest,$ans,1);
                   5875:             if ($bubble =~ /$matchon/ ) {
                   5876:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5877:                     if ($bubble == 0) {
                   5878:                         $bubble = 10; 
                   5879:                     }
                   5880:                     $record->{"scantron.$ansnum.answer"} = 
                   5881:                         $alphabet->[$bubble-1];
                   5882:                 } else {
                   5883:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5884:                 }
                   5885:             } else {
                   5886:                 $record->{"scantron.$ansnum.answer"}='';
                   5887:             }
                   5888:             $ansnum++;
                   5889:         }
                   5890:     } elsif (!defined($currquest)
                   5891:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5892:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5893:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5894:             $record->{"scantron.$ansnum.answer"}='';
                   5895:             $ansnum++;
                   5896:         }
                   5897:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5898:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5899:         }
                   5900:     } else {
                   5901:         if ($$scantron_config{'Qon'} eq 'number') {
                   5902:             $currquest = &digits_to_letters($currquest);            
                   5903:         }
                   5904:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5905:             my $bubble = substr($currquest,$ans,1);
                   5906:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5907:             $ansnum++;
                   5908:         }
                   5909:     }
                   5910:     return $ansnum;
                   5911: }
1.447     foxr     5912: 
1.503     raeburn  5913: sub scantron_validator_positional {
                   5914:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5915:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5916: 
1.503     raeburn  5917:     # Otherwise there's a positional notation;
                   5918:     # each bubble line requires Qlength items, and there are filled in
                   5919:     # bubbles for each case where there 'Qon' characters.
                   5920:     #
1.447     foxr     5921: 
1.503     raeburn  5922:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5923: 
1.503     raeburn  5924:     # If the split only gives us one element.. the full length of the
                   5925:     # answer string, no bubbles are filled in:
1.447     foxr     5926: 
1.507     raeburn  5927:     if ($answers_needed eq '') {
                   5928:         return;
                   5929:     }
                   5930: 
1.503     raeburn  5931:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5932:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5933:             $record->{"scantron.$ansnum.answer"}='';
                   5934:             $ansnum++;
                   5935:         }
                   5936:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5937:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5938:         }
                   5939:     } elsif (scalar(@array) == 2) {
                   5940:         my $location = length($array[0]);
                   5941:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5942:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5943:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5944:             if ($ans eq $line_num) {
                   5945:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5946:             } else {
                   5947:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5948:             }
                   5949:             $ansnum++;
                   5950:          }
                   5951:     } else {
                   5952:         #  If there's more than one instance of a bubble character
                   5953:         #  That's a double bubble; with positional notation we can
                   5954:         #  record all the bubbles filled in as well as the
                   5955:         #  fact this response consists of multiple bubbles.
                   5956:         #
                   5957:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5958:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5959:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5960:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5961:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5962:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5963:             my $doubleerror = 0;
                   5964:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5965:                    (!$doubleerror)) {
                   5966:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5967:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5968:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5969:                if (length(@currarray) > 2) {
                   5970:                    $doubleerror = 1;
                   5971:                } 
                   5972:             }
                   5973:             if ($doubleerror) {
                   5974:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5975:             }
                   5976:         } else {
                   5977:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5978:         }
                   5979:         my $item = $ansnum;
                   5980:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5981:             $record->{"scantron.$item.answer"} = '';
                   5982:             $item ++;
                   5983:         }
1.447     foxr     5984: 
1.503     raeburn  5985:         my @ans=@array;
                   5986:         my $i=0;
                   5987:         my $increment = 0;
                   5988:         while ($#ans) {
                   5989:             $i+=length($ans[0]) + $increment;
                   5990:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5991:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5992:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5993:             shift(@ans);
                   5994:             $increment = 1;
                   5995:         }
                   5996:         $ansnum += $answers_needed;
1.82      albertel 5997:     }
1.503     raeburn  5998:     return $ansnum;
1.82      albertel 5999: }
                   6000: 
1.423     albertel 6001: =pod
                   6002: 
                   6003: =item scantron_add_delay
                   6004: 
                   6005:    Adds an error message that occurred during the grading phase to a
                   6006:    queue of messages to be shown after grading pass is complete
                   6007: 
                   6008:  Arguments:
1.424     albertel 6009:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6010:    $scanline    - the scanline that caused the error
                   6011:    $errormesage - the error message
                   6012:    $errorcode   - a numeric code for the error
                   6013: 
                   6014:  Side Effects:
1.424     albertel 6015:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6016: 
                   6017: =cut
                   6018: 
1.82      albertel 6019: sub scantron_add_delay {
1.140     albertel 6020:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6021:     push(@$delayqueue,
                   6022: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6023: 	  'ecode' => $errorcode }
                   6024: 	 );
1.82      albertel 6025: }
                   6026: 
1.423     albertel 6027: =pod
                   6028: 
                   6029: =item scantron_find_student
                   6030: 
1.424     albertel 6031:    Finds the username for the current scanline
                   6032: 
                   6033:   Arguments:
                   6034:    $scantron_record - hash result from scantron_parse_scanline
                   6035:    $scan_data       - hash of correction information 
                   6036:                       (see &scantron_getfile() form more information)
                   6037:    $idmap           - hash from &username_to_idmap()
                   6038:    $line            - number of current scanline
                   6039:  
                   6040:   Returns:
                   6041:    Either 'username:domain' or undef if unknown
                   6042: 
1.423     albertel 6043: =cut
                   6044: 
1.82      albertel 6045: sub scantron_find_student {
1.157     albertel 6046:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6047:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6048:     if ($scanID =~ /^\s*$/) {
                   6049:  	return &scan_data($scan_data,"$line.user");
                   6050:     }
1.83      albertel 6051:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6052:  	if (lc($id) eq lc($scanID)) {
                   6053:  	    return $$idmap{$id};
                   6054:  	}
1.83      albertel 6055:     }
                   6056:     return undef;
                   6057: }
                   6058: 
1.423     albertel 6059: =pod
                   6060: 
                   6061: =item scantron_filter
                   6062: 
1.424     albertel 6063:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6064:    hidden resources was selected
                   6065: 
1.423     albertel 6066: =cut
                   6067: 
1.83      albertel 6068: sub scantron_filter {
                   6069:     my ($curres)=@_;
1.331     albertel 6070: 
                   6071:     if (ref($curres) && $curres->is_problem()) {
                   6072: 	# if the user has asked to not have either hidden
                   6073: 	# or 'randomout' controlled resources to be graded
                   6074: 	# don't include them
                   6075: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6076: 	    && $curres->randomout) {
                   6077: 	    return 0;
                   6078: 	}
1.83      albertel 6079: 	return 1;
                   6080:     }
                   6081:     return 0;
1.82      albertel 6082: }
                   6083: 
1.423     albertel 6084: =pod
                   6085: 
                   6086: =item scantron_process_corrections
                   6087: 
1.424     albertel 6088:    Gets correction information out of submitted form data and corrects
                   6089:    the scanline
                   6090: 
1.423     albertel 6091: =cut
                   6092: 
1.157     albertel 6093: sub scantron_process_corrections {
                   6094:     my ($r) = @_;
1.257     albertel 6095:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6096:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6097:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6098:     my $which=$env{'form.scantron_line'};
1.200     albertel 6099:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6100:     my ($skip,$err,$errmsg);
1.257     albertel 6101:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6102: 	$skip=1;
1.257     albertel 6103:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6104: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6105: 	    $env{'form.scantron_domain'};
1.157     albertel 6106: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6107: 	($line,$err,$errmsg)=
                   6108: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6109: 				     'ID',{'newid'=>$newid,
1.257     albertel 6110: 				    'username'=>$env{'form.scantron_username'},
                   6111: 				    'domain'=>$env{'form.scantron_domain'}});
                   6112:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6113: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6114: 	my $newCODE;
1.192     albertel 6115: 	my %args;
1.190     albertel 6116: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6117: 	    $newCODE='use_unfound';
1.190     albertel 6118: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6119: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6120: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6121: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6122: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6123: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6124: 	}
1.257     albertel 6125: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6126: 	    $args{'CODE_ignore_dup'}=1;
                   6127: 	}
                   6128: 	$args{'CODE'}=$newCODE;
1.186     albertel 6129: 	($line,$err,$errmsg)=
                   6130: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6131: 				     'CODE',\%args);
1.257     albertel 6132:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6133: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6134: 	    ($line,$err,$errmsg)=
                   6135: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6136: 					 $which,'answer',
                   6137: 					 { 'question'=>$question,
1.503     raeburn  6138: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6139:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6140: 	    if ($err) { last; }
                   6141: 	}
                   6142:     }
                   6143:     if ($err) {
1.398     albertel 6144: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6145:     } else {
1.200     albertel 6146: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6147: 	&scantron_putfile($scanlines,$scan_data);
                   6148:     }
                   6149: }
                   6150: 
1.423     albertel 6151: =pod
                   6152: 
                   6153: =item reset_skipping_status
                   6154: 
1.424     albertel 6155:    Forgets the current set of remember skipped scanlines (and thus
                   6156:    reverts back to considering all lines in the
                   6157:    scantron_skipped_<filename> file)
                   6158: 
1.423     albertel 6159: =cut
                   6160: 
1.200     albertel 6161: sub reset_skipping_status {
                   6162:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6163:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6164:     &scantron_putfile(undef,$scan_data);
                   6165: }
                   6166: 
1.423     albertel 6167: =pod
                   6168: 
                   6169: =item start_skipping
                   6170: 
1.424     albertel 6171:    Marks a scanline to be skipped. 
                   6172: 
1.423     albertel 6173: =cut
                   6174: 
1.376     albertel 6175: sub start_skipping {
1.200     albertel 6176:     my ($scan_data,$i)=@_;
                   6177:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6178:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6179: 	$remembered{$i}=2;
                   6180:     } else {
                   6181: 	$remembered{$i}=1;
                   6182:     }
1.200     albertel 6183:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6184: }
                   6185: 
1.423     albertel 6186: =pod
                   6187: 
                   6188: =item should_be_skipped
                   6189: 
1.424     albertel 6190:    Checks whether a scanline should be skipped.
                   6191: 
1.423     albertel 6192: =cut
                   6193: 
1.200     albertel 6194: sub should_be_skipped {
1.376     albertel 6195:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6196:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6197: 	# not redoing old skips
1.376     albertel 6198: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6199: 	return 0;
                   6200:     }
                   6201:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6202: 
                   6203:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6204: 	return 0;
                   6205:     }
1.200     albertel 6206:     return 1;
                   6207: }
                   6208: 
1.423     albertel 6209: =pod
                   6210: 
                   6211: =item remember_current_skipped
                   6212: 
1.424     albertel 6213:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6214:    file and remembers them into scan_data for later use.
                   6215: 
1.423     albertel 6216: =cut
                   6217: 
1.200     albertel 6218: sub remember_current_skipped {
                   6219:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6220:     my %to_remember;
                   6221:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6222: 	if ($scanlines->{'skipped'}[$i]) {
                   6223: 	    $to_remember{$i}=1;
                   6224: 	}
                   6225:     }
1.376     albertel 6226: 
1.200     albertel 6227:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6228:     &scantron_putfile(undef,$scan_data);
                   6229: }
                   6230: 
1.423     albertel 6231: =pod
                   6232: 
                   6233: =item check_for_error
                   6234: 
1.424     albertel 6235:     Checks if there was an error when attempting to remove a specific
                   6236:     scantron_.. bubble sheet data file. Prints out an error if
                   6237:     something went wrong.
                   6238: 
1.423     albertel 6239: =cut
                   6240: 
1.200     albertel 6241: sub check_for_error {
                   6242:     my ($r,$result)=@_;
                   6243:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6244: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6245:     }
                   6246: }
1.157     albertel 6247: 
1.423     albertel 6248: =pod
                   6249: 
                   6250: =item scantron_warning_screen
                   6251: 
1.424     albertel 6252:    Interstitial screen to make sure the operator has selected the
                   6253:    correct options before we start the validation phase.
                   6254: 
1.423     albertel 6255: =cut
                   6256: 
1.203     albertel 6257: sub scantron_warning_screen {
                   6258:     my ($button_text)=@_;
1.257     albertel 6259:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6260:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6261:     my $CODElist;
1.284     albertel 6262:     if ($scantron_config{'CODElocation'} &&
                   6263: 	$scantron_config{'CODEstart'} &&
                   6264: 	$scantron_config{'CODElength'}) {
                   6265: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6266: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6267: 	$CODElist=
1.492     albertel 6268: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6269: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6270:     }
1.492     albertel 6271:     return ('
1.203     albertel 6272: <p>
1.492     albertel 6273: <span class="LC_warning">
                   6274: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6275: </p>
                   6276: <table>
1.492     albertel 6277: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6278: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6279: '.$CODElist.'
1.203     albertel 6280: </table>
                   6281: <br />
1.492     albertel 6282: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6283: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6284: 
                   6285: <br />
1.492     albertel 6286: ');
1.203     albertel 6287: }
                   6288: 
1.423     albertel 6289: =pod
                   6290: 
                   6291: =item scantron_do_warning
                   6292: 
1.424     albertel 6293:    Check if the operator has picked something for all required
                   6294:    fields. Error out if something is missing.
                   6295: 
1.423     albertel 6296: =cut
                   6297: 
1.203     albertel 6298: sub scantron_do_warning {
                   6299:     my ($r)=@_;
1.324     albertel 6300:     my ($symb)=&get_symb($r);
1.203     albertel 6301:     if (!$symb) {return '';}
1.324     albertel 6302:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6303:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6304:     if ( $env{'form.selectpage'} eq '' ||
                   6305: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6306: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6307: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6308: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6309: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6310: 	} 
1.257     albertel 6311: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6312: 	    $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 6313: 	} 
1.257     albertel 6314: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6315: 	    $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 6316: 	} 
                   6317:     } else {
1.265     www      6318: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6319: 	$r->print('
                   6320: '.$warning.'
                   6321: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6322: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6323: ');
1.237     albertel 6324:     }
1.352     albertel 6325:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6326:     return '';
                   6327: }
                   6328: 
1.423     albertel 6329: =pod
                   6330: 
                   6331: =item scantron_form_start
                   6332: 
1.424     albertel 6333:     html hidden input for remembering all selected grading options
                   6334: 
1.423     albertel 6335: =cut
                   6336: 
1.203     albertel 6337: sub scantron_form_start {
                   6338:     my ($max_bubble)=@_;
                   6339:     my $result= <<SCANTRONFORM;
                   6340: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6341:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6342:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6343:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6344:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6345:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6346:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6347:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6348:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6349:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6350: SCANTRONFORM
1.447     foxr     6351: 
                   6352:   my $line = 0;
                   6353:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6354:        my $chunk =
                   6355: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6356:        $chunk .=
                   6357: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6358:        $chunk .= 
                   6359:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6360:        $chunk .=
                   6361:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6362:        $result .= $chunk;
                   6363:        $line++;
                   6364:    }
1.203     albertel 6365:     return $result;
                   6366: }
                   6367: 
1.423     albertel 6368: =pod
                   6369: 
                   6370: =item scantron_validate_file
                   6371: 
1.424     albertel 6372:     Dispatch routine for doing validation of a bubble sheet data file.
                   6373: 
                   6374:     Also processes any necessary information resets that need to
                   6375:     occur before validation begins (ignore previous corrections,
                   6376:     restarting the skipped records processing)
                   6377: 
1.423     albertel 6378: =cut
                   6379: 
1.157     albertel 6380: sub scantron_validate_file {
                   6381:     my ($r) = @_;
1.324     albertel 6382:     my ($symb)=&get_symb($r);
1.157     albertel 6383:     if (!$symb) {return '';}
1.324     albertel 6384:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6385:     
                   6386:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6387:     # them when doing the corrections reset
1.257     albertel 6388:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6389: 	&reset_skipping_status();
                   6390:     }
1.257     albertel 6391:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6392: 	&remember_current_skipped();
1.257     albertel 6393: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6394:     }
                   6395: 
1.257     albertel 6396:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6397: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6398: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6399: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6400: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6401:     }
1.200     albertel 6402: 
1.257     albertel 6403:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6404: 	&scantron_process_corrections($r);
                   6405:     }
1.503     raeburn  6406:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6407:     #get the student pick code ready
                   6408:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6409:     my $nav_error;
                   6410:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6411:     if ($nav_error) {
                   6412:         $r->print(&navmap_errormsg());
                   6413:         return '';
                   6414:     }
1.203     albertel 6415:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6416:     $r->print($result);
                   6417:     
1.334     albertel 6418:     my @validate_phases=( 'sequence',
                   6419: 			  'ID',
1.157     albertel 6420: 			  'CODE',
                   6421: 			  'doublebubble',
                   6422: 			  'missingbubbles');
1.257     albertel 6423:     if (!$env{'form.validatepass'}) {
                   6424: 	$env{'form.validatepass'} = 0;
1.157     albertel 6425:     }
1.257     albertel 6426:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6427: 
1.448     foxr     6428: 
1.157     albertel 6429:     my $stop=0;
                   6430:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6431: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6432: 	$r->rflush();
                   6433: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6434: 	{
                   6435: 	    no strict 'refs';
                   6436: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6437: 	}
                   6438:     }
                   6439:     if (!$stop) {
1.203     albertel 6440: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6441: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6442:                   $warning.
                   6443:                   &mt('Perform verification for each student after storage of submissions?').
                   6444:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6445:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6446:                   ('&nbsp;'x3).'<label>'.
                   6447:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6448:                   '</label></span><br />'.
                   6449:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6450:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
1.542     raeburn  6451:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6452:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6453:     } else {
                   6454: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6455: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6456:     }
                   6457:     if ($stop) {
1.334     albertel 6458: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6459: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6460: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6461: 
1.492     albertel 6462: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6463: 	} else {
1.503     raeburn  6464:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6465: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6466:             } else {
1.539     riegler  6467:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6468:             }
1.492     albertel 6469: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6470: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6471: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6472: 	}
1.157     albertel 6473:     }
1.352     albertel 6474:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6475:     return '';
                   6476: }
                   6477: 
1.423     albertel 6478: 
                   6479: =pod
                   6480: 
                   6481: =item scantron_remove_file
                   6482: 
1.424     albertel 6483:    Removes the requested bubble sheet data file, makes sure that
                   6484:    scantron_original_<filename> is never removed
                   6485: 
                   6486: 
1.423     albertel 6487: =cut
                   6488: 
1.200     albertel 6489: sub scantron_remove_file {
1.192     albertel 6490:     my ($which)=@_;
1.257     albertel 6491:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6492:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6493:     my $file='scantron_';
1.200     albertel 6494:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6495: 	$file.=$which.'_';
1.192     albertel 6496:     } else {
                   6497: 	return 'refused';
                   6498:     }
1.257     albertel 6499:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6500:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6501: }
                   6502: 
1.423     albertel 6503: 
                   6504: =pod
                   6505: 
                   6506: =item scantron_remove_scan_data
                   6507: 
1.424     albertel 6508:    Removes all scan_data correction for the requested bubble sheet
                   6509:    data file.  (In the case that both the are doing skipped records we need
                   6510:    to remember the old skipped lines for the time being so that element
                   6511:    persists for a while.)
                   6512: 
1.423     albertel 6513: =cut
                   6514: 
1.200     albertel 6515: sub scantron_remove_scan_data {
1.257     albertel 6516:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6517:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6518:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6519:     my @todelete;
1.257     albertel 6520:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6521:     foreach my $key (@keys) {
                   6522: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6523: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6524: 		$key=~/remember_skipping/) {
                   6525: 		next;
                   6526: 	    }
1.192     albertel 6527: 	    push(@todelete,$key);
                   6528: 	}
                   6529:     }
1.200     albertel 6530:     my $result;
1.192     albertel 6531:     if (@todelete) {
1.491     albertel 6532: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6533: 				       \@todelete,$cdom,$cname);
                   6534:     } else {
                   6535: 	$result = 'ok';
1.192     albertel 6536:     }
                   6537:     return $result;
                   6538: }
                   6539: 
1.423     albertel 6540: 
                   6541: =pod
                   6542: 
                   6543: =item scantron_getfile
                   6544: 
1.424     albertel 6545:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6546:     the scan_data hash
                   6547:   
                   6548:   Arguments:
                   6549:     None
                   6550: 
                   6551:   Returns:
                   6552:     2 hash references
                   6553: 
                   6554:      - first one has 
                   6555:          orig      -
                   6556:          corrected -
                   6557:          skipped   -  each of which points to an array ref of the specified
                   6558:                       file broken up into individual lines
                   6559:          count     - number of scanlines
                   6560:  
                   6561:      - second is the scan_data hash possible keys are
1.425     albertel 6562:        ($number refers to scanline numbered $number and thus the key affects
                   6563:         only that scanline
                   6564:         $bubline refers to the specific bubble line element and the aspects
                   6565:         refers to that specific bubble line element)
                   6566: 
                   6567:        $number.user - username:domain to use
                   6568:        $number.CODE_ignore_dup 
                   6569:                     - ignore the duplicate CODE error 
                   6570:        $number.useCODE
                   6571:                     - use the CODE in the scanline as is
                   6572:        $number.no_bubble.$bubline
                   6573:                     - it is valid that there is no bubbled in bubble
                   6574:                       at $number $bubline
                   6575:        remember_skipping
                   6576:                     - a frozen hash containing keys of $number and values
                   6577:                       of either 
                   6578:                         1 - we are on a 'do skipped records pass' and plan
                   6579:                             on processing this line
                   6580:                         2 - we are on a 'do skipped records pass' and this
                   6581:                             scanline has been marked to skip yet again
1.424     albertel 6582: 
1.423     albertel 6583: =cut
                   6584: 
1.157     albertel 6585: sub scantron_getfile {
1.200     albertel 6586:     #FIXME really would prefer a scantron directory
1.257     albertel 6587:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6588:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6589:     my $lines;
                   6590:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6591: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6592:     my %scanlines;
                   6593:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6594:     my $temp=$scanlines{'orig'};
                   6595:     $scanlines{'count'}=$#$temp;
                   6596: 
                   6597:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6598: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6599:     if ($lines eq '-1') {
                   6600: 	$scanlines{'corrected'}=[];
                   6601:     } else {
                   6602: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6603:     }
                   6604:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6605: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6606:     if ($lines eq '-1') {
                   6607: 	$scanlines{'skipped'}=[];
                   6608:     } else {
                   6609: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6610:     }
1.175     albertel 6611:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6612:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6613:     my %scan_data = @tmp;
                   6614:     return (\%scanlines,\%scan_data);
                   6615: }
                   6616: 
1.423     albertel 6617: =pod
                   6618: 
                   6619: =item lonnet_putfile
                   6620: 
1.424     albertel 6621:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6622: 
                   6623:  Arguments:
                   6624:    $contents - data to store
                   6625:    $filename - filename to store $contents into
                   6626: 
                   6627:  Returns:
                   6628:    result value from &Apache::lonnet::finishuserfileupload
                   6629: 
1.423     albertel 6630: =cut
                   6631: 
1.157     albertel 6632: sub lonnet_putfile {
                   6633:     my ($contents,$filename)=@_;
1.257     albertel 6634:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6635:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6636:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6637:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6638: 
                   6639: }
                   6640: 
1.423     albertel 6641: =pod
                   6642: 
                   6643: =item scantron_putfile
                   6644: 
1.424     albertel 6645:     Stores the current version of the bubble sheet data files, and the
                   6646:     scan_data hash. (Does not modify the original version only the
                   6647:     corrected and skipped versions.
                   6648: 
                   6649:  Arguments:
                   6650:     $scanlines - hash ref that looks like the first return value from
                   6651:                  &scantron_getfile()
                   6652:     $scan_data - hash ref that looks like the second return value from
                   6653:                  &scantron_getfile()
                   6654: 
1.423     albertel 6655: =cut
                   6656: 
1.157     albertel 6657: sub scantron_putfile {
                   6658:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6659:     #FIXME really would prefer a scantron directory
1.257     albertel 6660:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6661:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6662:     if ($scanlines) {
                   6663: 	my $prefix='scantron_';
1.157     albertel 6664: # no need to update orig, shouldn't change
                   6665: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6666: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6667: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6668: 			$prefix.'corrected_'.
1.257     albertel 6669: 			$env{'form.scantron_selectfile'});
1.200     albertel 6670: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6671: 			$prefix.'skipped_'.
1.257     albertel 6672: 			$env{'form.scantron_selectfile'});
1.200     albertel 6673:     }
1.175     albertel 6674:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6675: }
                   6676: 
1.423     albertel 6677: =pod
                   6678: 
                   6679: =item scantron_get_line
                   6680: 
1.424     albertel 6681:    Returns the correct version of the scanline
                   6682: 
                   6683:  Arguments:
                   6684:     $scanlines - hash ref that looks like the first return value from
                   6685:                  &scantron_getfile()
                   6686:     $scan_data - hash ref that looks like the second return value from
                   6687:                  &scantron_getfile()
                   6688:     $i         - number of the requested line (starts at 0)
                   6689: 
                   6690:  Returns:
                   6691:    A scanline, (either the original or the corrected one if it
                   6692:    exists), or undef if the requested scanline should be
                   6693:    skipped. (Either because it's an skipped scanline, or it's an
                   6694:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6695:    pass.
                   6696: 
1.423     albertel 6697: =cut
                   6698: 
1.157     albertel 6699: sub scantron_get_line {
1.200     albertel 6700:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6701:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6702:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6703:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6704:     return $scanlines->{'orig'}[$i]; 
                   6705: }
                   6706: 
1.423     albertel 6707: =pod
                   6708: 
                   6709: =item scantron_todo_count
                   6710: 
1.424     albertel 6711:     Counts the number of scanlines that need processing.
                   6712: 
                   6713:  Arguments:
                   6714:     $scanlines - hash ref that looks like the first return value from
                   6715:                  &scantron_getfile()
                   6716:     $scan_data - hash ref that looks like the second return value from
                   6717:                  &scantron_getfile()
                   6718: 
                   6719:  Returns:
                   6720:     $count - number of scanlines to process
                   6721: 
1.423     albertel 6722: =cut
                   6723: 
1.200     albertel 6724: sub get_todo_count {
                   6725:     my ($scanlines,$scan_data)=@_;
                   6726:     my $count=0;
                   6727:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6728: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6729: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6730: 	$count++;
                   6731:     }
                   6732:     return $count;
                   6733: }
                   6734: 
1.423     albertel 6735: =pod
                   6736: 
                   6737: =item scantron_put_line
                   6738: 
1.424     albertel 6739:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6740:     data file.
                   6741: 
                   6742:  Arguments:
                   6743:     $scanlines - hash ref that looks like the first return value from
                   6744:                  &scantron_getfile()
                   6745:     $scan_data - hash ref that looks like the second return value from
                   6746:                  &scantron_getfile()
                   6747:     $i         - line number to update
                   6748:     $newline   - contents of the updated scanline
                   6749:     $skip      - if true make the line for skipping and update the
                   6750:                  'skipped' file
                   6751: 
1.423     albertel 6752: =cut
                   6753: 
1.157     albertel 6754: sub scantron_put_line {
1.200     albertel 6755:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6756:     if ($skip) {
                   6757: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6758: 	&start_skipping($scan_data,$i);
1.157     albertel 6759: 	return;
                   6760:     }
                   6761:     $scanlines->{'corrected'}[$i]=$newline;
                   6762: }
                   6763: 
1.423     albertel 6764: =pod
                   6765: 
                   6766: =item scantron_clear_skip
                   6767: 
1.424     albertel 6768:    Remove a line from the 'skipped' file
                   6769: 
                   6770:  Arguments:
                   6771:     $scanlines - hash ref that looks like the first return value from
                   6772:                  &scantron_getfile()
                   6773:     $scan_data - hash ref that looks like the second return value from
                   6774:                  &scantron_getfile()
                   6775:     $i         - line number to update
                   6776: 
1.423     albertel 6777: =cut
                   6778: 
1.376     albertel 6779: sub scantron_clear_skip {
                   6780:     my ($scanlines,$scan_data,$i)=@_;
                   6781:     if (exists($scanlines->{'skipped'}[$i])) {
                   6782: 	undef($scanlines->{'skipped'}[$i]);
                   6783: 	return 1;
                   6784:     }
                   6785:     return 0;
                   6786: }
                   6787: 
1.423     albertel 6788: =pod
                   6789: 
                   6790: =item scantron_filter_not_exam
                   6791: 
1.424     albertel 6792:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6793:    filter out resources that are not marked as 'exam' mode
                   6794: 
1.423     albertel 6795: =cut
                   6796: 
1.334     albertel 6797: sub scantron_filter_not_exam {
                   6798:     my ($curres)=@_;
                   6799:     
                   6800:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6801: 	# if the user has asked to not have either hidden
                   6802: 	# or 'randomout' controlled resources to be graded
                   6803: 	# don't include them
                   6804: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6805: 	    && $curres->randomout) {
                   6806: 	    return 0;
                   6807: 	}
                   6808: 	return 1;
                   6809:     }
                   6810:     return 0;
                   6811: }
                   6812: 
1.423     albertel 6813: =pod
                   6814: 
                   6815: =item scantron_validate_sequence
                   6816: 
1.424     albertel 6817:     Validates the selected sequence, checking for resource that are
                   6818:     not set to exam mode.
                   6819: 
1.423     albertel 6820: =cut
                   6821: 
1.334     albertel 6822: sub scantron_validate_sequence {
                   6823:     my ($r,$currentphase) = @_;
                   6824: 
                   6825:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6826:     unless (ref($navmap)) {
                   6827:         $r->print(&navmap_errormsg());
                   6828:         return (1,$currentphase);
                   6829:     }
1.334     albertel 6830:     my (undef,undef,$sequence)=
                   6831: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6832: 
                   6833:     my $map=$navmap->getResourceByUrl($sequence);
                   6834: 
                   6835:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6836:                                     value="ignore" />');
                   6837:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6838: 	my @resources=
                   6839: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6840: 	if (@resources) {
1.357     banghart 6841: 	    $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 6842: 	    return (1,$currentphase);
                   6843: 	}
                   6844:     }
                   6845: 
                   6846:     return (0,$currentphase+1);
                   6847: }
                   6848: 
1.423     albertel 6849: 
                   6850: 
1.157     albertel 6851: sub scantron_validate_ID {
                   6852:     my ($r,$currentphase) = @_;
                   6853:     
                   6854:     #get student info
                   6855:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6856:     my %idmap=&username_to_idmap($classlist);
                   6857: 
                   6858:     #get scantron line setup
1.257     albertel 6859:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6860:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6861: 
                   6862:     my $nav_error;
                   6863:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6864:     if ($nav_error) {
                   6865:         $r->print(&navmap_errormsg());
                   6866:         return(1,$currentphase);
                   6867:     }
1.157     albertel 6868: 
                   6869:     my %found=('ids'=>{},'usernames'=>{});
                   6870:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6871: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6872: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6873: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6874: 						 $scan_data);
                   6875: 	my $id=$$scan_record{'scantron.ID'};
                   6876: 	my $found;
                   6877: 	foreach my $checkid (keys(%idmap)) {
                   6878: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6879: 	}
                   6880: 	if ($found) {
                   6881: 	    my $username=$idmap{$found};
                   6882: 	    if ($found{'ids'}{$found}) {
                   6883: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6884: 					 $line,'duplicateID',$found);
1.194     albertel 6885: 		return(1,$currentphase);
1.157     albertel 6886: 	    } elsif ($found{'usernames'}{$username}) {
                   6887: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6888: 					 $line,'duplicateID',$username);
1.194     albertel 6889: 		return(1,$currentphase);
1.157     albertel 6890: 	    }
1.186     albertel 6891: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6892: 	    $found{'ids'}{$found}++;
                   6893: 	    $found{'usernames'}{$username}++;
                   6894: 	} else {
                   6895: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6896: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6897: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6898: 		    &scantron_get_correction($r,$i,$scan_record,
                   6899: 					     \%scantron_config,
                   6900: 					     $line,'duplicateID',$username);
1.194     albertel 6901: 		    return(1,$currentphase);
1.157     albertel 6902: 		} elsif (!defined($username)) {
                   6903: 		    &scantron_get_correction($r,$i,$scan_record,
                   6904: 					     \%scantron_config,
                   6905: 					     $line,'incorrectID');
1.194     albertel 6906: 		    return(1,$currentphase);
1.157     albertel 6907: 		}
                   6908: 		$found{'usernames'}{$username}++;
                   6909: 	    } else {
                   6910: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6911: 					 $line,'incorrectID');
1.194     albertel 6912: 		return(1,$currentphase);
1.157     albertel 6913: 	    }
                   6914: 	}
                   6915:     }
                   6916: 
                   6917:     return (0,$currentphase+1);
                   6918: }
                   6919: 
1.423     albertel 6920: 
1.157     albertel 6921: sub scantron_get_correction {
                   6922:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6923: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6924: #to show both the current line and the previous one and allow skipping
                   6925: #the previous one or the current one
                   6926: 
1.333     albertel 6927:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6928: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6929: 			    " for PaperID <tt>[_1]</tt>",
                   6930: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6931:     } else {
1.492     albertel 6932: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6933: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6934: 			    $i,$line)."</p> \n");
                   6935:     }
                   6936:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6937: 			  "The name on the paper is [_2],[_3]",
                   6938: 			  $$scan_record{'scantron.ID'},
                   6939: 			  $$scan_record{'scantron.LastName'},
                   6940: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6941: 
1.157     albertel 6942:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6943:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6944:                            # Array populated for doublebubble or
                   6945:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6946:                            # to validate radio button checking   
                   6947: 
1.157     albertel 6948:     if ($error =~ /ID$/) {
1.186     albertel 6949: 	if ($error eq 'incorrectID') {
1.492     albertel 6950: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6951: 		      "</p>\n");
1.157     albertel 6952: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6953: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6954: 	}
1.242     albertel 6955: 	$r->print($message);
1.492     albertel 6956: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6957: 	$r->print("\n<ul><li> ");
                   6958: 	#FIXME it would be nice if this sent back the user ID and
                   6959: 	#could do partial userID matches
                   6960: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6961: 				       'scantron_username','scantron_domain'));
                   6962: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6963: 	$r->print("\n@".
1.257     albertel 6964: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6965: 
                   6966: 	$r->print('</li>');
1.186     albertel 6967:     } elsif ($error =~ /CODE$/) {
                   6968: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6969: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6970: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6971: 	    $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 6972: 	}
1.492     albertel 6973: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6974: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6975: 	$r->print($message);
1.492     albertel 6976: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6977: 	$r->print("\n<br /> ");
1.194     albertel 6978: 	my $i=0;
1.273     albertel 6979: 	if ($error eq 'incorrectCODE' 
                   6980: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6981: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6982: 	    if ($closest > 0) {
                   6983: 		foreach my $testcode (@{$closest}) {
                   6984: 		    my $checked='';
1.569     bisitz   6985: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6986: 		    $r->print("
                   6987:    <label>
1.569     bisitz   6988:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6989:        ".&mt("Use the similar CODE [_1] instead.",
                   6990: 	    "<b><tt>".$testcode."</tt></b>")."
                   6991:     </label>
                   6992:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6993: 		    $r->print("\n<br />");
                   6994: 		    $i++;
                   6995: 		}
1.194     albertel 6996: 	    }
                   6997: 	}
1.273     albertel 6998: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6999: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7000: 	    $r->print("
                   7001:     <label>
1.569     bisitz   7002:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 7003:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   7004: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7005:     </label>");
1.273     albertel 7006: 	    $r->print("\n<br />");
                   7007: 	}
1.194     albertel 7008: 
1.597     wenzelju 7009: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7010: function change_radio(field) {
1.190     albertel 7011:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7012:     var i;
                   7013:     for (i=0;i<slct.length;i++) {
                   7014:         if (slct[i].value==field) { slct[i].checked=true; }
                   7015:     }
                   7016: }
                   7017: ENDSCRIPT
1.187     albertel 7018: 	my $href="/adm/pickcode?".
1.359     www      7019: 	   "form=".&escape("scantronupload").
                   7020: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7021: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7022: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7023: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7024: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7025: 	    $r->print("
                   7026:     <label>
                   7027:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7028:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7029: 	     "<a target='_blank' href='$href'>","</a>")."
                   7030:     </label> 
1.558     bisitz   7031:     ".&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 7032: 	    $r->print("\n<br />");
                   7033: 	}
1.492     albertel 7034: 	$r->print("
                   7035:     <label>
                   7036:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7037:        ".&mt("Use [_1] as the CODE.",
                   7038: 	     "</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 7039: 	$r->print("\n<br /><br />");
1.157     albertel 7040:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  7041: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7042: 
                   7043: 	# The form field scantron_questions is acutally a list of line numbers.
                   7044: 	# represented by this form so:
                   7045: 
                   7046: 	my $line_list = &questions_to_line_list($arg);
                   7047: 
1.157     albertel 7048: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7049: 		  $line_list.'" />');
1.242     albertel 7050: 	$r->print($message);
1.492     albertel 7051: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7052: 	foreach my $question (@{$arg}) {
1.503     raeburn  7053: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7054:                                                    $scan_record, $error);
1.524     raeburn  7055:             push(@lines_to_correct,@linenums);
1.157     albertel 7056: 	}
1.503     raeburn  7057:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7058:     } elsif ($error eq 'missingbubble') {
1.492     albertel 7059: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 7060: 	$r->print($message);
1.492     albertel 7061: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7062: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7063: 
1.503     raeburn  7064: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7065: 	# a list of question numbers. Therefore:
                   7066: 	#
                   7067: 	
                   7068: 	my $line_list = &questions_to_line_list($arg);
                   7069: 
1.157     albertel 7070: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7071: 		  $line_list.'" />');
1.157     albertel 7072: 	foreach my $question (@{$arg}) {
1.503     raeburn  7073: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7074:                                                    $scan_record, $error);
1.524     raeburn  7075:             push(@lines_to_correct,@linenums);
1.157     albertel 7076: 	}
1.503     raeburn  7077:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7078:     } else {
                   7079: 	$r->print("\n<ul>");
                   7080:     }
                   7081:     $r->print("\n</li></ul>");
1.497     foxr     7082: }
                   7083: 
1.503     raeburn  7084: sub verify_bubbles_checked {
                   7085:     my (@ansnums) = @_;
                   7086:     my $ansnumstr = join('","',@ansnums);
                   7087:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7088:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7089: function verify_bubble_radio(form) {
                   7090:     var ansnumArray = new Array ("$ansnumstr");
                   7091:     var need_bubble_count = 0;
                   7092:     for (var i=0; i<ansnumArray.length; i++) {
                   7093:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7094:             var bubble_picked = 0; 
                   7095:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7096:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7097:                     bubble_picked = 1;
                   7098:                 }
                   7099:             }
                   7100:             if (bubble_picked == 0) {
                   7101:                 need_bubble_count ++;
                   7102:             }
                   7103:         }
                   7104:     }
                   7105:     if (need_bubble_count) {
                   7106:         alert("$warning");
                   7107:         return;
                   7108:     }
                   7109:     form.submit(); 
                   7110: }
                   7111: ENDSCRIPT
                   7112:     return $output;
                   7113: }
                   7114: 
1.497     foxr     7115: =pod
                   7116: 
                   7117: =item  questions_to_line_list
1.157     albertel 7118: 
1.497     foxr     7119: Converts a list of questions into a string of comma separated
                   7120: line numbers in the answer sheet used by the questions.  This is
                   7121: used to fill in the scantron_questions form field.
                   7122: 
                   7123:   Arguments:
                   7124:      questions    - Reference to an array of questions.
                   7125: 
                   7126: =cut
                   7127: 
                   7128: 
                   7129: sub questions_to_line_list {
                   7130:     my ($questions) = @_;
                   7131:     my @lines;
                   7132: 
1.503     raeburn  7133:     foreach my $item (@{$questions}) {
                   7134:         my $question = $item;
                   7135:         my ($first,$count,$last);
                   7136:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7137:             $question = $1;
                   7138:             my $subquestion = $2;
                   7139:             $first = $first_bubble_line{$question-1} + 1;
                   7140:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7141:             my $subcount = 1;
                   7142:             while ($subcount<$subquestion) {
                   7143:                 $first += $subans[$subcount-1];
                   7144:                 $subcount ++;
                   7145:             }
                   7146:             $count = $subans[$subquestion-1];
                   7147:         } else {
                   7148: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7149: 	    $count   = $bubble_lines_per_response{$question-1};
                   7150:         }
1.506     raeburn  7151:         $last = $first+$count-1;
1.503     raeburn  7152:         push(@lines, ($first..$last));
1.497     foxr     7153:     }
                   7154:     return join(',', @lines);
                   7155: }
                   7156: 
                   7157: =pod 
                   7158: 
                   7159: =item prompt_for_corrections
                   7160: 
                   7161: Prompts for a potentially multiline correction to the
                   7162: user's bubbling (factors out common code from scantron_get_correction
                   7163: for multi and missing bubble cases).
                   7164: 
                   7165:  Arguments:
                   7166:    $r           - Apache request object.
                   7167:    $question    - The question number to prompt for.
                   7168:    $scan_config - The scantron file configuration hash.
                   7169:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7170:    $error       - Type of error
1.497     foxr     7171: 
                   7172:  Implicit inputs:
                   7173:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7174:                                   Numbered from 0 (but question numbers are from
                   7175:                                   1.
                   7176:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7177:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7178:                                   type problems render as separate sub-questions, 
1.503     raeburn  7179:                                   in exam mode. This hash contains a 
                   7180:                                   comma-separated list of the lines per 
                   7181:                                   sub-question.
1.510     raeburn  7182:    %responsetype_per_response   - essayresponse, formularesponse,
                   7183:                                   stringresponse, imageresponse, reactionresponse,
                   7184:                                   and organicresponse type problem parts can have
1.503     raeburn  7185:                                   multiple lines per response if the weight
                   7186:                                   assigned exceeds 10.  In this case, only
                   7187:                                   one bubble per line is permitted, but more 
                   7188:                                   than one line might contain bubbles, e.g.
                   7189:                                   bubbling of: line 1 - J, line 2 - J, 
                   7190:                                   line 3 - B would assign 22 points.  
1.497     foxr     7191: 
                   7192: =cut
                   7193: 
                   7194: sub prompt_for_corrections {
1.503     raeburn  7195:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7196:     my ($current_line,$lines);
                   7197:     my @linenums;
                   7198:     my $questionnum = $question;
                   7199:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7200:         $question = $1;
                   7201:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7202:         my $subquestion = $2;
                   7203:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7204:         my $subcount = 1;
                   7205:         while ($subcount<$subquestion) {
                   7206:             $current_line += $subans[$subcount-1];
                   7207:             $subcount ++;
                   7208:         }
                   7209:         $lines = $subans[$subquestion-1];
                   7210:     } else {
                   7211:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7212:         $lines        = $bubble_lines_per_response{$question-1};
                   7213:     }
1.497     foxr     7214:     if ($lines > 1) {
1.503     raeburn  7215:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7216:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7217:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7218:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7219:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7220:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7221:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7222:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
1.503     raeburn  7223:         } else {
                   7224:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7225:         }
1.497     foxr     7226:     }
                   7227:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7228:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7229: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7230: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7231:         push(@linenums,$current_line);
1.497     foxr     7232: 	$current_line++;
                   7233:     }
                   7234:     if ($lines > 1) {
                   7235: 	$r->print("<hr /><br />");
                   7236:     }
1.503     raeburn  7237:     return @linenums;
1.157     albertel 7238: }
1.423     albertel 7239: 
                   7240: =pod
                   7241: 
                   7242: =item scantron_bubble_selector
                   7243:   
                   7244:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7245:    possibly showing the existing the selected bubbles if known
1.423     albertel 7246: 
                   7247:  Arguments:
                   7248:     $r           - Apache request object
                   7249:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7250:     $line        - Number of the line being displayed.
1.503     raeburn  7251:     $questionnum - Question number (may include subquestion)
                   7252:     $error       - Type of error.
1.497     foxr     7253:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7254: 
                   7255: =cut
                   7256: 
1.157     albertel 7257: sub scantron_bubble_selector {
1.503     raeburn  7258:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7259:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7260: 
                   7261:     my $scmode=$$scan_config{'Qon'};
                   7262:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7263: 
1.157     albertel 7264:     my @alphabet=('A'..'Z');
1.503     raeburn  7265:     $r->print(&Apache::loncommon::start_data_table().
                   7266:               &Apache::loncommon::start_data_table_row());
                   7267:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7268:     for (my $i=0;$i<$max+1;$i++) {
                   7269: 	$r->print("\n".'<td align="center">');
                   7270: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7271: 	else { $r->print('&nbsp;'); }
                   7272: 	$r->print('</td>');
                   7273:     }
1.503     raeburn  7274:     $r->print(&Apache::loncommon::end_data_table_row().
                   7275:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7276:     for (my $i=0;$i<$max;$i++) {
                   7277: 	$r->print("\n".
                   7278: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7279: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7280:     }
1.503     raeburn  7281:     my $nobub_checked = ' ';
                   7282:     if ($error eq 'missingbubble') {
                   7283:         $nobub_checked = ' checked = "checked" ';
                   7284:     }
                   7285:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7286: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7287:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7288:               $line.'" value="'.$questionnum.'" /></td>');
                   7289:     $r->print(&Apache::loncommon::end_data_table_row().
                   7290:               &Apache::loncommon::end_data_table());
1.157     albertel 7291: }
                   7292: 
1.423     albertel 7293: =pod
                   7294: 
                   7295: =item num_matches
                   7296: 
1.424     albertel 7297:    Counts the number of characters that are the same between the two arguments.
                   7298: 
                   7299:  Arguments:
                   7300:    $orig - CODE from the scanline
                   7301:    $code - CODE to match against
                   7302: 
                   7303:  Returns:
                   7304:    $count - integer count of the number of same characters between the
                   7305:             two arguments
                   7306: 
1.423     albertel 7307: =cut
                   7308: 
1.194     albertel 7309: sub num_matches {
                   7310:     my ($orig,$code) = @_;
                   7311:     my @code=split(//,$code);
                   7312:     my @orig=split(//,$orig);
                   7313:     my $same=0;
                   7314:     for (my $i=0;$i<scalar(@code);$i++) {
                   7315: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7316:     }
                   7317:     return $same;
                   7318: }
                   7319: 
1.423     albertel 7320: =pod
                   7321: 
                   7322: =item scantron_get_closely_matching_CODEs
                   7323: 
1.424     albertel 7324:    Cycles through all CODEs and finds the set that has the greatest
                   7325:    number of same characters as the provided CODE
                   7326: 
                   7327:  Arguments:
                   7328:    $allcodes - hash ref returned by &get_codes()
                   7329:    $CODE     - CODE from the current scanline
                   7330: 
                   7331:  Returns:
                   7332:    2 element list
                   7333:     - first elements is number of how closely matching the best fit is 
                   7334:       (5 means best set has 5 matching characters)
                   7335:     - second element is an arrary ref containing the set of valid CODEs
                   7336:       that best fit the passed in CODE
                   7337: 
1.423     albertel 7338: =cut
                   7339: 
1.194     albertel 7340: sub scantron_get_closely_matching_CODEs {
                   7341:     my ($allcodes,$CODE)=@_;
                   7342:     my @CODEs;
                   7343:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7344: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7345:     }
                   7346: 
                   7347:     return ($#CODEs,$CODEs[-1]);
                   7348: }
                   7349: 
1.423     albertel 7350: =pod
                   7351: 
                   7352: =item get_codes
                   7353: 
1.424     albertel 7354:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7355:    set of remembered CODEs.
                   7356: 
                   7357:  Arguments:
                   7358:   $old_name - name of the set of remembered CODEs
                   7359:   $cdom     - domain of the course
                   7360:   $cnum     - internal course name
                   7361: 
                   7362:  Returns:
                   7363:   %allcodes - keys are the valid CODEs, values are all 1
                   7364: 
1.423     albertel 7365: =cut
                   7366: 
1.194     albertel 7367: sub get_codes {
1.280     foxr     7368:     my ($old_name, $cdom, $cnum) = @_;
                   7369:     if (!$old_name) {
                   7370: 	$old_name=$env{'form.scantron_CODElist'};
                   7371:     }
                   7372:     if (!$cdom) {
                   7373: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7374:     }
                   7375:     if (!$cnum) {
                   7376: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7377:     }
1.278     albertel 7378:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7379: 				    $cdom,$cnum);
                   7380:     my %allcodes;
                   7381:     if ($result{"type\0$old_name"} eq 'number') {
                   7382: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7383:     } else {
                   7384: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7385:     }
1.194     albertel 7386:     return %allcodes;
                   7387: }
                   7388: 
1.423     albertel 7389: =pod
                   7390: 
                   7391: =item scantron_validate_CODE
                   7392: 
1.424     albertel 7393:    Validates all scanlines in the selected file to not have any
                   7394:    invalid or underspecified CODEs and that none of the codes are
                   7395:    duplicated if this was requested.
                   7396: 
1.423     albertel 7397: =cut
                   7398: 
1.157     albertel 7399: sub scantron_validate_CODE {
                   7400:     my ($r,$currentphase) = @_;
1.257     albertel 7401:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7402:     if ($scantron_config{'CODElocation'} &&
                   7403: 	$scantron_config{'CODEstart'} &&
                   7404: 	$scantron_config{'CODElength'}) {
1.257     albertel 7405: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7406: 	    &FIXME_blow_up()
                   7407: 	}
                   7408:     } else {
                   7409: 	return (0,$currentphase+1);
                   7410:     }
                   7411:     
                   7412:     my %usedCODEs;
                   7413: 
1.194     albertel 7414:     my %allcodes=&get_codes();
1.186     albertel 7415: 
1.582     raeburn  7416:     my $nav_error;
                   7417:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7418:     if ($nav_error) {
                   7419:         $r->print(&navmap_errormsg());
                   7420:         return(1,$currentphase);
                   7421:     }
1.447     foxr     7422: 
1.186     albertel 7423:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7424:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7425: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7426: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7427: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7428: 						 $scan_data);
                   7429: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7430: 	my $error=0;
1.224     albertel 7431: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7432: 	    &scantron_get_correction($r,$i,$scan_record,
                   7433: 				     \%scantron_config,
                   7434: 				     $line,'incorrectCODE',\%allcodes);
                   7435: 	    return(1,$currentphase);
                   7436: 	}
1.221     albertel 7437: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7438: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7439: 	    &scantron_get_correction($r,$i,$scan_record,
                   7440: 				     \%scantron_config,
1.194     albertel 7441: 				     $line,'incorrectCODE',\%allcodes);
                   7442: 	    return(1,$currentphase);
1.186     albertel 7443: 	}
1.214     albertel 7444: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7445: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7446: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7447: 	    &scantron_get_correction($r,$i,$scan_record,
                   7448: 				     \%scantron_config,
1.194     albertel 7449: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7450: 	    return(1,$currentphase);
1.186     albertel 7451: 	}
1.524     raeburn  7452: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7453:     }
1.157     albertel 7454:     return (0,$currentphase+1);
                   7455: }
                   7456: 
1.423     albertel 7457: =pod
                   7458: 
                   7459: =item scantron_validate_doublebubble
                   7460: 
1.424     albertel 7461:    Validates all scanlines in the selected file to not have any
                   7462:    bubble lines with multiple bubbles marked.
                   7463: 
1.423     albertel 7464: =cut
                   7465: 
1.157     albertel 7466: sub scantron_validate_doublebubble {
                   7467:     my ($r,$currentphase) = @_;
                   7468:     #get student info
                   7469:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7470:     my %idmap=&username_to_idmap($classlist);
                   7471: 
                   7472:     #get scantron line setup
1.257     albertel 7473:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7474:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7475:     my $nav_error;
                   7476:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7477:     if ($nav_error) {
                   7478:         $r->print(&navmap_errormsg());
                   7479:         return(1,$currentphase);
                   7480:     }
1.447     foxr     7481: 
1.157     albertel 7482:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7483: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7484: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7485: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7486: 						 $scan_data);
                   7487: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7488: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7489: 				 'doublebubble',
                   7490: 				 $$scan_record{'scantron.doubleerror'});
                   7491:     	return (1,$currentphase);
                   7492:     }
                   7493:     return (0,$currentphase+1);
                   7494: }
                   7495: 
1.423     albertel 7496: 
1.503     raeburn  7497: sub scantron_get_maxbubble {
1.582     raeburn  7498:     my ($nav_error) = @_;
1.257     albertel 7499:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7500: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7501: 	&restore_bubble_lines();
1.257     albertel 7502: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7503:     }
1.330     albertel 7504: 
1.447     foxr     7505:     my (undef, undef, $sequence) =
1.257     albertel 7506: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7507: 
1.447     foxr     7508:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7509:     unless (ref($navmap)) {
                   7510:         if (ref($nav_error)) {
                   7511:             $$nav_error = 1;
                   7512:         }
1.591     raeburn  7513:         return;
1.582     raeburn  7514:     }
1.191     albertel 7515:     my $map=$navmap->getResourceByUrl($sequence);
                   7516:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7517: 
                   7518:     &Apache::lonxml::clear_problem_counter();
                   7519: 
1.557     raeburn  7520:     my $uname       = $env{'user.name'};
                   7521:     my $udom        = $env{'user.domain'};
1.435     foxr     7522:     my $cid         = $env{'request.course.id'};
                   7523:     my $total_lines = 0;
                   7524:     %bubble_lines_per_response = ();
1.447     foxr     7525:     %first_bubble_line         = ();
1.503     raeburn  7526:     %subdivided_bubble_lines   = ();
                   7527:     %responsetype_per_response = ();
1.554     raeburn  7528: 
1.447     foxr     7529:     my $response_number = 0;
                   7530:     my $bubble_line     = 0;
1.191     albertel 7531:     foreach my $resource (@resources) {
1.542     raeburn  7532:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7533:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7534: 	    foreach my $part_id (@{$parts}) {
                   7535:                 my $lines;
                   7536: 
                   7537: 	        # TODO - make this a persistent hash not an array.
                   7538: 
                   7539:                 # optionresponse, matchresponse and rankresponse type items 
                   7540:                 # render as separate sub-questions in exam mode.
                   7541:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7542:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7543:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7544:                     my ($numbub,$numshown);
                   7545:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7546:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7547:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7548:                         }
                   7549:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7550:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7551:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7552:                         }
                   7553:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7554:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7555:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7556:                         }
                   7557:                     }
                   7558:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7559:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7560:                     }
                   7561:                     my $bubbles_per_line = 10;
                   7562:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7563:                     if (($numbub % $bubbles_per_line) != 0) {
                   7564:                         $inner_bubble_lines++;
                   7565:                     }
                   7566:                     for (my $i=0; $i<$numshown; $i++) {
                   7567:                         $subdivided_bubble_lines{$response_number} .= 
                   7568:                             $inner_bubble_lines.',';
                   7569:                     }
                   7570:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7571:                     $lines = $numshown * $inner_bubble_lines;
                   7572:                 } else {
                   7573:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7574:                 } 
                   7575: 
                   7576:                 $first_bubble_line{$response_number} = $bubble_line;
                   7577: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7578:                 $responsetype_per_response{$response_number} = 
                   7579:                     $analysis->{$part_id.'.type'};
                   7580: 	        $response_number++;
                   7581: 
                   7582: 	        $bubble_line +=  $lines;
                   7583: 	        $total_lines +=  $lines;
                   7584: 	    }
                   7585:         }
                   7586:     }
1.552     raeburn  7587:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7588: 
                   7589:     &save_bubble_lines();
                   7590:     $env{'form.scantron_maxbubble'} =
                   7591: 	$total_lines;
                   7592:     return $env{'form.scantron_maxbubble'};
                   7593: }
1.523     raeburn  7594: 
1.157     albertel 7595: sub scantron_validate_missingbubbles {
                   7596:     my ($r,$currentphase) = @_;
                   7597:     #get student info
                   7598:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7599:     my %idmap=&username_to_idmap($classlist);
                   7600: 
                   7601:     #get scantron line setup
1.257     albertel 7602:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7603:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7604:     my $nav_error;
                   7605:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7606:     if ($nav_error) {
                   7607:         return(1,$currentphase);
                   7608:     }
1.157     albertel 7609:     if (!$max_bubble) { $max_bubble=2**31; }
                   7610:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7611: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7612: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7613: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7614: 						 $scan_data);
                   7615: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7616: 	my @to_correct;
1.470     foxr     7617: 	
                   7618: 	# Probably here's where the error is...
                   7619: 
1.157     albertel 7620: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7621:             my $lastbubble;
                   7622:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7623:                my $question = $1;
                   7624:                my $subquestion = $2;
                   7625:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7626:                my $first = $first_bubble_line{$question-1};
                   7627:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7628:                my $subcount = 1;
                   7629:                while ($subcount<$subquestion) {
                   7630:                    $first += $subans[$subcount-1];
                   7631:                    $subcount ++;
                   7632:                }
                   7633:                my $count = $subans[$subquestion-1];
                   7634:                $lastbubble = $first + $count;
                   7635:             } else {
                   7636:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7637:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7638:             }
                   7639:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7640: 	    push(@to_correct,$missing);
                   7641: 	}
                   7642: 	if (@to_correct) {
                   7643: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7644: 				     $line,'missingbubble',\@to_correct);
                   7645: 	    return (1,$currentphase);
                   7646: 	}
                   7647: 
                   7648:     }
                   7649:     return (0,$currentphase+1);
                   7650: }
                   7651: 
1.423     albertel 7652: 
1.82      albertel 7653: sub scantron_process_students {
1.75      albertel 7654:     my ($r) = @_;
1.513     foxr     7655: 
1.257     albertel 7656:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7657:     my ($symb)=&get_symb($r);
1.513     foxr     7658:     if (!$symb) {
                   7659: 	return '';
                   7660:     }
1.324     albertel 7661:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7662: 
1.257     albertel 7663:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7664:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7665:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7666:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7667:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7668:     unless (ref($navmap)) {
                   7669:         $r->print(&navmap_errormsg());
                   7670:         return '';
                   7671:     }  
1.83      albertel 7672:     my $map=$navmap->getResourceByUrl($sequence);
                   7673:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7674:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7675:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7676:                             \%grader_randomlists_by_symb);
1.586     raeburn  7677:     my $resource_error;
1.557     raeburn  7678:     foreach my $resource (@resources) {
1.586     raeburn  7679:         my $ressymb;
                   7680:         if (ref($resource)) {
                   7681:             $ressymb = $resource->symb();
                   7682:         } else {
                   7683:             $resource_error = 1;
                   7684:             last;
                   7685:         }
1.557     raeburn  7686:         my ($analysis,$parts) =
                   7687:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7688:                                       $env{'user.name'},$env{'user.domain'},1);
                   7689:         $grader_partids_by_symb{$ressymb} = $parts;
                   7690:         if (ref($analysis) eq 'HASH') {
                   7691:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7692:                 $grader_randomlists_by_symb{$ressymb} = 
                   7693:                     $analysis->{'parts_withrandomlist'};
                   7694:             }
                   7695:         }
                   7696:     }
1.586     raeburn  7697:     if ($resource_error) {
                   7698:         $r->print(&navmap_errormsg());
                   7699:         return '';
                   7700:     }
1.557     raeburn  7701: 
1.554     raeburn  7702:     my ($uname,$udom);
1.82      albertel 7703:     my $result= <<SCANTRONFORM;
1.81      albertel 7704: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7705:   <input type="hidden" name="command" value="scantron_configphase" />
                   7706:   $default_form_data
                   7707: SCANTRONFORM
1.82      albertel 7708:     $r->print($result);
                   7709: 
                   7710:     my @delayqueue;
1.542     raeburn  7711:     my (%completedstudents,%scandata);
1.140     albertel 7712:     
1.520     www      7713:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7714:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7715:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7716:  				    'Bubblesheet Progress',$count,
1.195     albertel 7717: 				    'inline',undef,'scantronupload');
1.140     albertel 7718:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7719: 					  'Processing first student');
1.542     raeburn  7720:     $r->print('<br />');
1.140     albertel 7721:     my $start=&Time::HiRes::time();
1.158     albertel 7722:     my $i=-1;
1.542     raeburn  7723:     my $started;
1.447     foxr     7724: 
1.582     raeburn  7725:     my $nav_error;
                   7726:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7727:     if ($nav_error) {
                   7728:         $r->print(&navmap_errormsg());
                   7729:         return '';
                   7730:     }
                   7731: 
1.513     foxr     7732:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7733:     # the user and return.
                   7734: 
                   7735:     if ($ssi_error) {
                   7736: 	$r->print("</form>");
                   7737: 	&ssi_print_error($r);
                   7738: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7739:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7740: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7741:     }
1.447     foxr     7742: 
1.542     raeburn  7743:     my %lettdig = &letter_to_digits();
                   7744:     my $numletts = scalar(keys(%lettdig));
                   7745: 
1.157     albertel 7746:     while ($i<$scanlines->{'count'}) {
                   7747:  	($uname,$udom)=('','');
                   7748:  	$i++;
1.200     albertel 7749:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7750:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7751: 	if ($started) {
                   7752: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7753: 						     'last student');
                   7754: 	}
                   7755: 	$started=1;
1.157     albertel 7756:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7757:  						 $scan_data);
                   7758:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7759:  					      \%idmap,$i)) {
                   7760:   	    &scantron_add_delay(\@delayqueue,$line,
                   7761:  				'Unable to find a student that matches',1);
                   7762:  	    next;
                   7763:   	}
                   7764:  	if (exists $completedstudents{$uname}) {
                   7765:  	    &scantron_add_delay(\@delayqueue,$line,
                   7766:  				'Student '.$uname.' has multiple sheets',2);
                   7767:  	    next;
                   7768:  	}
                   7769:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7770: 
1.586     raeburn  7771:         my (%partids_by_symb,$res_error);
1.554     raeburn  7772:         foreach my $resource (@resources) {
1.586     raeburn  7773:             my $ressymb;
                   7774:             if (ref($resource)) {
                   7775:                 $ressymb = $resource->symb();
                   7776:             } else {
                   7777:                 $res_error = 1;
                   7778:                 last;
                   7779:             }
1.557     raeburn  7780:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7781:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7782:                 my ($analysis,$parts) =
                   7783:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7784:                 $partids_by_symb{$ressymb} = $parts;
                   7785:             } else {
                   7786:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7787:             }
1.554     raeburn  7788:         }
                   7789: 
1.586     raeburn  7790:         if ($res_error) {
                   7791:             &scantron_add_delay(\@delayqueue,$line,
                   7792:                                 'An error occurred while grading student '.$uname,2);
                   7793:             next;
                   7794:         }
                   7795: 
1.330     albertel 7796: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7797:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7798: 
                   7799: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7800: 	    &scantron_putfile($scanlines,$scan_data);
                   7801: 	}
1.161     albertel 7802: 	
1.542     raeburn  7803:         my $scancode;
                   7804:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7805:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7806:             $scancode = $scan_record->{'scantron.CODE'};
                   7807:         } else {
                   7808:             $scancode = '';
                   7809:         }
                   7810: 
                   7811:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7812:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7813:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7814:             $r->print("</form>");
                   7815:             &ssi_print_error($r);
                   7816:             $r->print(&show_grading_menu_form($symb));
                   7817:             &Apache::lonnet::remove_lock($lock);
                   7818:             return '';      # Why return ''?  Beats me.
                   7819:         }
1.513     foxr     7820: 
1.140     albertel 7821: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7822:         if ($env{'form.verifyrecord'}) {
                   7823:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7824:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7825:             chomp($studentdata);
                   7826:             $studentdata =~ s/\r$//;
                   7827:             my $studentrecord = '';
                   7828:             my $counter = -1;
                   7829:             foreach my $resource (@resources) {
1.554     raeburn  7830:                 my $ressymb = $resource->symb();
1.542     raeburn  7831:                 ($counter,my $recording) =
                   7832:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7833:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7834:                                              \%scantron_config,\%lettdig,$numletts);
                   7835:                 $studentrecord .= $recording;
                   7836:             }
                   7837:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7838:                 &Apache::lonxml::clear_problem_counter();
                   7839:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7840:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7841:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7842:                     $r->print("</form>");
                   7843:                     &ssi_print_error($r);
                   7844:                     $r->print(&show_grading_menu_form($symb));
                   7845:                     &Apache::lonnet::remove_lock($lock);
                   7846:                     delete($completedstudents{$uname});
                   7847:                     return '';
                   7848:                 }
1.542     raeburn  7849:                 $counter = -1;
                   7850:                 $studentrecord = '';
                   7851:                 foreach my $resource (@resources) {
1.554     raeburn  7852:                     my $ressymb = $resource->symb();
1.542     raeburn  7853:                     ($counter,my $recording) =
                   7854:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7855:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7856:                                                  \%scantron_config,\%lettdig,$numletts);
                   7857:                     $studentrecord .= $recording;
                   7858:                 }
                   7859:                 if ($studentrecord ne $studentdata) {
                   7860:                     $r->print('<p><span class="LC_error">');
                   7861:                     if ($scancode eq '') {
                   7862:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7863:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7864:                     } else {
                   7865:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7866:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7867:                     }
                   7868:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7869:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7870:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7871:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7872:                               &Apache::loncommon::start_data_table_row().
                   7873:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7874:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7875:                               &Apache::loncommon::end_data_table_row().
                   7876:                               &Apache::loncommon::start_data_table_row().
                   7877:                               '<td>Stored submissions</td>'.
                   7878:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7879:                               &Apache::loncommon::end_data_table_row().
                   7880:                               &Apache::loncommon::end_data_table().'</p>');
                   7881:                 } else {
                   7882:                     $r->print('<br /><span class="LC_warning">'.
                   7883:                              &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 />'.
                   7884:                              &mt("As a consequence, this user's submission history records two tries.").
                   7885:                                  '</span><br />');
                   7886:                 }
                   7887:             }
                   7888:         }
1.543     raeburn  7889:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7890:     } continue {
1.330     albertel 7891: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7892: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7893:     }
1.140     albertel 7894:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7895:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7896: #    my $lasttime = &Time::HiRes::time()-$start;
                   7897: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7898: 
1.200     albertel 7899:     $r->print("</form>");
1.324     albertel 7900:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7901:     return '';
1.75      albertel 7902: }
1.157     albertel 7903: 
1.557     raeburn  7904: sub graders_resources_pass {
                   7905:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7906:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7907:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7908:         foreach my $resource (@{$resources}) {
                   7909:             my $ressymb = $resource->symb();
                   7910:             my ($analysis,$parts) =
                   7911:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7912:                                           $env{'user.name'},$env{'user.domain'},1);
                   7913:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7914:             if (ref($analysis) eq 'HASH') {
                   7915:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7916:                     $grader_randomlists_by_symb->{$ressymb} =
                   7917:                         $analysis->{'parts_withrandomlist'};
                   7918:                 }
                   7919:             }
                   7920:         }
                   7921:     }
                   7922:     return;
                   7923: }
                   7924: 
1.542     raeburn  7925: sub grade_student_bubbles {
1.554     raeburn  7926:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7927:     if (ref($resources) eq 'ARRAY') {
                   7928:         my $count = 0;
                   7929:         foreach my $resource (@{$resources}) {
                   7930:             my $ressymb = $resource->symb();
                   7931:             my %form = ('submitted'      => 'scantron',
                   7932:                         'grade_target'   => 'grade',
                   7933:                         'grade_username' => $uname,
                   7934:                         'grade_domain'   => $udom,
                   7935:                         'grade_courseid' => $env{'request.course.id'},
                   7936:                         'grade_symb'     => $ressymb,
                   7937:                         'CODE'           => $scancode
                   7938:                        );
                   7939:             if (ref($parts) eq 'HASH') {
                   7940:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7941:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7942:                         $form{'scantron_questnum_start.'.$part} =
                   7943:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7944:                         $count++;
                   7945:                     }
                   7946:                 }
                   7947:             }
                   7948:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7949:             return 'ssi_error' if ($ssi_error);
                   7950:             last if (&Apache::loncommon::connection_aborted($r));
                   7951:         }
1.542     raeburn  7952:     }
                   7953:     return;
                   7954: }
                   7955: 
1.157     albertel 7956: sub scantron_upload_scantron_data {
                   7957:     my ($r)=@_;
1.565     raeburn  7958:     my $dom = $env{'request.role.domain'};
                   7959:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7960:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7961:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7962: 							  'domainid',
1.565     raeburn  7963: 							  'coursename',$dom);
                   7964:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7965:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 7966:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  7967:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7968:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
1.597     wenzelju 7969:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7970:     function checkUpload(formname) {
                   7971: 	if (formname.upfile.value == "") {
1.579     raeburn  7972: 	    alert("'.$nofile_alert.'");
1.157     albertel 7973: 	    return false;
                   7974: 	}
1.565     raeburn  7975:         if (formname.courseid.value == "") {
1.579     raeburn  7976:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7977:             return false;
                   7978:         }
1.157     albertel 7979: 	formname.submit();
                   7980:     }
1.565     raeburn  7981: 
                   7982:     function ToSyllabus() {
                   7983:         var cdom = '."'$dom'".';
                   7984:         var cnum = document.rules.courseid.value;
                   7985:         if (cdom == "" || cdom == null) {
                   7986:             return;
                   7987:         }
                   7988:         if (cnum == "" || cnum == null) {
                   7989:            return;
                   7990:         }
                   7991:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7992:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7993:         return;
                   7994:     }
                   7995: 
1.597     wenzelju 7996: '));
                   7997:     $r->print('
1.566     raeburn  7998: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7999: 
1.492     albertel 8000: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8001: '.$default_form_data.
                   8002:   &Apache::lonhtmlcommon::start_pick_box().
                   8003:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8004:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8005:   &Apache::lonhtmlcommon::row_closure().
                   8006:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8007:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8008:   &Apache::lonhtmlcommon::row_closure().
                   8009:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8010:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8011:   &Apache::lonhtmlcommon::row_closure().
                   8012:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8013:   '<input type="file" name="upfile" size="50" />'.
                   8014:   &Apache::lonhtmlcommon::row_closure(1).
                   8015:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8016: 
1.492     albertel 8017: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8018: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8019: </form>
1.492     albertel 8020: ');
1.157     albertel 8021:     return '';
                   8022: }
                   8023: 
1.423     albertel 8024: 
1.157     albertel 8025: sub scantron_upload_scantron_data_save {
                   8026:     my($r)=@_;
1.324     albertel 8027:     my ($symb)=&get_symb($r,1);
1.182     albertel 8028:     my $doanotherupload=
                   8029: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8030: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8031: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8032: 	'</form>'."\n";
1.257     albertel 8033:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8034: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8035: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8036: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 8037: 	if ($symb) {
1.324     albertel 8038: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 8039: 	} else {
                   8040: 	    $r->print($doanotherupload);
                   8041: 	}
1.162     albertel 8042: 	return '';
                   8043:     }
1.257     albertel 8044:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8045:     my $uploadedfile;
1.567     raeburn  8046:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8047:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8048:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8049:     } else {
1.568     raeburn  8050:         my $result = 
                   8051:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8052:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8053: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8054: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8055:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8056: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8057:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8058:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8059:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8060: 	} else {
1.567     raeburn  8061: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8062:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8063: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8064: 	}
                   8065:     }
1.174     albertel 8066:     if ($symb) {
1.209     ng       8067: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8068:     } else {
1.182     albertel 8069: 	$r->print($doanotherupload);
1.174     albertel 8070:     }
1.157     albertel 8071:     return '';
                   8072: }
                   8073: 
1.567     raeburn  8074: sub validate_uploaded_scantron_file {
                   8075:     my ($cdom,$cname,$fname) = @_;
                   8076:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8077:     my @lines;
                   8078:     if ($scanlines ne '-1') {
                   8079:         @lines=split("\n",$scanlines,-1);
                   8080:     }
                   8081:     my $output;
                   8082:     if (@lines) {
                   8083:         my (%counts,$max_match_format);
                   8084:         my ($max_match_count,$max_match_pct) = (0,0);
                   8085:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8086:         my %idmap = &username_to_idmap($classlist);
                   8087:         foreach my $key (keys(%idmap)) {
                   8088:             my $lckey = lc($key);
                   8089:             $idmap{$lckey} = $idmap{$key};
                   8090:         }
                   8091:         my %unique_formats;
                   8092:         my @formatlines = &get_scantronformat_file();
                   8093:         foreach my $line (@formatlines) {
                   8094:             chomp($line);
                   8095:             my @config = split(/:/,$line);
                   8096:             my $idstart = $config[5];
                   8097:             my $idlength = $config[6];
                   8098:             if (($idstart ne '') && ($idlength > 0)) {
                   8099:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8100:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8101:                 } else {
                   8102:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8103:                 }
                   8104:             }
                   8105:         }
                   8106:         foreach my $key (keys(%unique_formats)) {
                   8107:             my ($idstart,$idlength) = split(':',$key);
                   8108:             %{$counts{$key}} = (
                   8109:                                'found'   => 0,
                   8110:                                'total'   => 0,
                   8111:                               );
                   8112:             foreach my $line (@lines) {
                   8113:                 next if ($line =~ /^#/);
                   8114:                 next if ($line =~ /^[\s\cz]*$/);
                   8115:                 my $id = substr($line,$idstart-1,$idlength);
                   8116:                 $id = lc($id);
                   8117:                 if (exists($idmap{$id})) {
                   8118:                     $counts{$key}{'found'} ++;
                   8119:                 }
                   8120:                 $counts{$key}{'total'} ++;
                   8121:             }
                   8122:             if ($counts{$key}{'total'}) {
                   8123:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8124:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8125:                     $max_match_pct = $percent_match;
                   8126:                     $max_match_format = $key;
                   8127:                     $max_match_count = $counts{$key}{'total'};
                   8128:                 }
                   8129:             }
                   8130:         }
                   8131:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8132:             my $format_descs;
                   8133:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8134:             for (my $i=0; $i<$numwithformat; $i++) {
                   8135:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8136:                 if ($i<$numwithformat-2) {
                   8137:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8138:                 } elsif ($i==$numwithformat-2) {
                   8139:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8140:                 } elsif ($i==$numwithformat-1) {
                   8141:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8142:                 }
                   8143:             }
                   8144:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8145:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8146:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8147:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8148:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8149:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8150:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8151:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8152:                        '</ul>';
                   8153:         }
                   8154:     } else {
                   8155:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8156:     }
                   8157:     return $output;
                   8158: }
                   8159: 
1.202     albertel 8160: sub valid_file {
                   8161:     my ($requested_file)=@_;
                   8162:     foreach my $filename (sort(&scantron_filenames())) {
                   8163: 	if ($requested_file eq $filename) { return 1; }
                   8164:     }
                   8165:     return 0;
                   8166: }
                   8167: 
                   8168: sub scantron_download_scantron_data {
                   8169:     my ($r)=@_;
1.324     albertel 8170:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8171:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8172:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8173:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8174:     if (! &valid_file($file)) {
1.492     albertel 8175: 	$r->print('
1.202     albertel 8176: 	<p>
1.492     albertel 8177: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8178:         </p>
1.492     albertel 8179: ');
1.324     albertel 8180: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8181: 	return;
                   8182:     }
                   8183:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8184:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8185:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8186:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8187:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8188:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8189:     $r->print('
1.202     albertel 8190:     <p>
1.492     albertel 8191: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8192: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8193:     </p>
                   8194:     <p>
1.492     albertel 8195: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8196: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8197:     </p>
                   8198:     <p>
1.492     albertel 8199: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8200: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8201:     </p>
1.492     albertel 8202: ');
1.324     albertel 8203:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8204:     return '';
                   8205: }
1.157     albertel 8206: 
1.523     raeburn  8207: sub checkscantron_results {
                   8208:     my ($r) = @_;
                   8209:     my ($symb)=&get_symb($r);
                   8210:     if (!$symb) {return '';}
                   8211:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8212:     my $cid = $env{'request.course.id'};
1.542     raeburn  8213:     my %lettdig = &letter_to_digits();
1.523     raeburn  8214:     my $numletts = scalar(keys(%lettdig));
                   8215:     my $cnum = $env{'course.'.$cid.'.num'};
                   8216:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8217:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8218:     my %record;
                   8219:     my %scantron_config =
                   8220:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8221:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8222:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8223:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8224:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8225:     unless (ref($navmap)) {
                   8226:         $r->print(&navmap_errormsg());
                   8227:         return '';
                   8228:     }
1.523     raeburn  8229:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8230:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8231:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8232:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8233: 
1.554     raeburn  8234:     my ($uname,$udom);
1.523     raeburn  8235:     my (%scandata,%lastname,%bylast);
                   8236:     $r->print('
                   8237: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8238: 
                   8239:     my @delayqueue;
                   8240:     my %completedstudents;
                   8241: 
                   8242:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8243:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8244:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8245:                                     'inline',undef,'checkscantron');
1.546     raeburn  8246:     my ($username,$domain,$started);
1.582     raeburn  8247:     my $nav_error;
                   8248:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8249:     if ($nav_error) {
                   8250:         $r->print(&navmap_errormsg());
                   8251:         return '';
                   8252:     }
1.523     raeburn  8253: 
                   8254:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8255:                                           'Processing first student');
                   8256:     my $start=&Time::HiRes::time();
                   8257:     my $i=-1;
                   8258: 
                   8259:     while ($i<$scanlines->{'count'}) {
                   8260:         ($username,$domain,$uname)=('','','');
                   8261:         $i++;
                   8262:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8263:         if ($line=~/^[\s\cz]*$/) { next; }
                   8264:         if ($started) {
                   8265:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8266:                                                      'last student');
                   8267:         }
                   8268:         $started=1;
                   8269:         my $scan_record=
                   8270:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8271:                                                      $scan_data);
                   8272:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8273:                                                               \%idmap,$i)) {
                   8274:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8275:                                 'Unable to find a student that matches',1);
                   8276:             next;
                   8277:         }
                   8278:         if (exists $completedstudents{$uname}) {
                   8279:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8280:                                 'Student '.$uname.' has multiple sheets',2);
                   8281:             next;
                   8282:         }
                   8283:         my $pid = $scan_record->{'scantron.ID'};
                   8284:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8285:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8286:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8287:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8288:         chomp($scandata{$pid});
                   8289:         $scandata{$pid} =~ s/\r$//;
                   8290:         ($username,$domain)=split(/:/,$uname);
                   8291:         my $counter = -1;
                   8292:         foreach my $resource (@resources) {
1.557     raeburn  8293:             my $parts;
1.554     raeburn  8294:             my $ressymb = $resource->symb();
1.557     raeburn  8295:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8296:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8297:                 (my $analysis,$parts) =
                   8298:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8299:             } else {
                   8300:                 $parts = $grader_partids_by_symb{$ressymb};
                   8301:             }
1.542     raeburn  8302:             ($counter,my $recording) =
                   8303:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8304:                                          $scandata{$pid},$parts,
1.542     raeburn  8305:                                          \%scantron_config,\%lettdig,$numletts);
                   8306:             $record{$pid} .= $recording;
1.523     raeburn  8307:         }
                   8308:     }
                   8309:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8310:     $r->print('<br />');
                   8311:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8312:     $passed = 0;
                   8313:     $failed = 0;
                   8314:     $numstudents = 0;
                   8315:     foreach my $last (sort(keys(%bylast))) {
                   8316:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8317:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8318:                 my $showscandata = $scandata{$pid};
                   8319:                 my $showrecord = $record{$pid};
                   8320:                 $showscandata =~ s/\s/&nbsp;/g;
                   8321:                 $showrecord =~ s/\s/&nbsp;/g;
                   8322:                 if ($scandata{$pid} eq $record{$pid}) {
                   8323:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8324:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8325: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8326: '</tr>'."\n".
                   8327: '<tr class="'.$css_class.'">'."\n".
                   8328: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8329:                     $passed ++;
                   8330:                 } else {
                   8331:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8332:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Bubblesheet').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8333: '</tr>'."\n".
                   8334: '<tr class="'.$css_class.'">'."\n".
                   8335: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8336: '</tr>'."\n";
                   8337:                     $failed ++;
                   8338:                 }
                   8339:                 $numstudents ++;
                   8340:             }
                   8341:         }
                   8342:     }
1.572     www      8343:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
1.523     raeburn  8344:     $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>');
                   8345:     if ($passed) {
1.572     www      8346:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8347:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8348:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8349:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8350:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8351:                  $okstudents."\n".
                   8352:                  &Apache::loncommon::end_data_table().'<br />');
                   8353:     }
                   8354:     if ($failed) {
1.572     www      8355:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8356:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8357:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8358:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8359:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8360:                  $badstudents."\n".
                   8361:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8362:                  &mt('Differences can occur if submissions were modified using manual grading after a bubblesheet grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original bubblesheets.');  
1.523     raeburn  8363:     }
                   8364:     $r->print('</form><br />'.$grading_menu_button);
                   8365:     return;
                   8366: }
                   8367: 
1.542     raeburn  8368: sub verify_scantron_grading {
1.554     raeburn  8369:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8370:         $scantron_config,$lettdig,$numletts) = @_;
                   8371:     my ($record,%expected,%startpos);
                   8372:     return ($counter,$record) if (!ref($resource));
                   8373:     return ($counter,$record) if (!$resource->is_problem());
                   8374:     my $symb = $resource->symb();
1.554     raeburn  8375:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8376:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8377:         $counter ++;
                   8378:         $expected{$part_id} = 0;
                   8379:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8380:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8381:             foreach my $item (@sub_lines) {
                   8382:                 $expected{$part_id} += $item;
                   8383:             }
                   8384:         } else {
                   8385:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8386:         }
                   8387:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8388:     }
                   8389:     if ($symb) {
                   8390:         my %recorded;
                   8391:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8392:         if ($returnhash{'version'}) {
                   8393:             my %lasthash=();
                   8394:             my $version;
                   8395:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8396:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8397:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8398:                 }
                   8399:             }
                   8400:             foreach my $key (keys(%lasthash)) {
                   8401:                 if ($key =~ /\.scantron$/) {
                   8402:                     my $value = &unescape($lasthash{$key});
                   8403:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8404:                     if ($value eq '') {
                   8405:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8406:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8407:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8408:                             }
                   8409:                         }
                   8410:                     } else {
                   8411:                         my @tocheck;
                   8412:                         my @items = split(//,$value);
                   8413:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8414:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8415:                             if (@items < $expected{$part_id}) {
                   8416:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8417:                                 my @singles = split(//,$fragment);
                   8418:                                 foreach my $pos (@singles) {
                   8419:                                     if ($pos eq ' ') {
                   8420:                                         push(@tocheck,$pos);
                   8421:                                     } else {
                   8422:                                         my $next = shift(@items);
                   8423:                                         push(@tocheck,$next);
                   8424:                                     }
                   8425:                                 }
                   8426:                             } else {
                   8427:                                 @tocheck = @items;
                   8428:                             }
                   8429:                             foreach my $letter (@tocheck) {
                   8430:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8431:                                     if ($letter !~ /^[A-J]$/) {
                   8432:                                         $letter = $scantron_config->{'Qoff'};
                   8433:                                     }
                   8434:                                     $recorded{$part_id} .= $letter;
                   8435:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8436:                                     my $digit;
                   8437:                                     if ($letter !~ /^[A-J]$/) {
                   8438:                                         $digit = $scantron_config->{'Qoff'};
                   8439:                                     } else {
                   8440:                                         $digit = $lettdig->{$letter};
                   8441:                                     }
                   8442:                                     $recorded{$part_id} .= $digit;
                   8443:                                 }
                   8444:                             }
                   8445:                         } else {
                   8446:                             @tocheck = @items;
                   8447:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8448:                                 my $curr_sub = shift(@tocheck);
                   8449:                                 my $digit;
                   8450:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8451:                                     $digit = $lettdig->{$curr_sub}-1;
                   8452:                                 }
                   8453:                                 if ($curr_sub eq 'J') {
                   8454:                                     $digit += scalar($numletts);
                   8455:                                 }
                   8456:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8457:                                     if ($j == $digit) {
                   8458:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8459:                                     } else {
                   8460:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8461:                                     }
                   8462:                                 }
                   8463:                             }
                   8464:                         }
                   8465:                     }
                   8466:                 }
                   8467:             }
                   8468:         }
1.554     raeburn  8469:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8470:             if ($recorded{$part_id} eq '') {
                   8471:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8472:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8473:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8474:                     }
                   8475:                 }
                   8476:             }
                   8477:             $record .= $recorded{$part_id};
                   8478:         }
                   8479:     }
                   8480:     return ($counter,$record);
                   8481: }
                   8482: 
                   8483: sub letter_to_digits { 
                   8484:     my %lettdig = (
                   8485:                     A => 1,
                   8486:                     B => 2,
                   8487:                     C => 3,
                   8488:                     D => 4,
                   8489:                     E => 5,
                   8490:                     F => 6,
                   8491:                     G => 7,
                   8492:                     H => 8,
                   8493:                     I => 9,
                   8494:                     J => 0,
                   8495:                   );
                   8496:     return %lettdig;
                   8497: }
                   8498: 
1.423     albertel 8499: 
1.75      albertel 8500: #-------- end of section for handling grading scantron forms -------
                   8501: #
                   8502: #-------------------------------------------------------------------
                   8503: 
1.72      ng       8504: #-------------------------- Menu interface -------------------------
                   8505: #
                   8506: #--- Show a Grading Menu button - Calls the next routine ---
                   8507: sub show_grading_menu_form {
1.324     albertel 8508:     my ($symb)=@_;
1.125     ng       8509:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8510: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8511: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8512: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8513: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8514: 	'</form>'."\n";
                   8515:     return $result;
                   8516: }
                   8517: 
1.77      ng       8518: # -- Retrieve choices for grading form
                   8519: sub savedState {
                   8520:     my %savedState = ();
1.257     albertel 8521:     if ($env{'form.saveState'}) {
                   8522: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8523: 	    my ($key,$value) = split(/=/,$_,2);
                   8524: 	    $savedState{$key} = $value;
                   8525: 	}
                   8526:     }
                   8527:     return \%savedState;
                   8528: }
1.76      ng       8529: 
1.443     banghart 8530: sub grading_menu {
                   8531:     my ($request) = @_;
                   8532:     my ($symb)=&get_symb($request);
                   8533:     if (!$symb) {return '';}
                   8534:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8535: 
1.598   ! www      8536: #    $request->print($table);
1.443     banghart 8537:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8538:                   'probTitle'=>$probTitle,
1.598   ! www      8539:                   'command'=>'individual',
1.443     banghart 8540:                   'saveState'=>"",
                   8541:                   'gradingMenu'=>1,
                   8542:                   'showgrading'=>"yes");
1.538     schulted 8543:     
1.598   ! www      8544:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
        !          8545: 
        !          8546:     $fields{'command'}='ungraded';
        !          8547:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
        !          8548: 
        !          8549:     $fields{'command'}='table';
        !          8550:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
        !          8551: 
        !          8552:     $fields{'command'}='all_for_one';
        !          8553:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
        !          8554: 
1.443     banghart 8555:     $fields{'command'} = 'csvform';
1.538     schulted 8556:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8557:     
1.443     banghart 8558:     $fields{'command'} = 'processclicker';
1.538     schulted 8559:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8560:     
1.443     banghart 8561:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8562:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8563:     
1.598   ! www      8564:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8565:             items =>[
1.598   ! www      8566:                         {	linktext => 'Select individual students to grade',
        !          8567:                     		url => $url1a,
1.538     schulted 8568:                     		permission => 'F',
                   8569:                     		icon => 'edit-find-replace.png',
1.598   ! www      8570:                     		linktitle => 'Grade current resource for a selection of students.'
        !          8571:                         }, 
        !          8572:                         {       linktext => 'Grade ungraded submissions.',
        !          8573:                                 url => $url1b,
        !          8574:                                 permission => 'F',
        !          8575:                                 icon => 'edit-find-replace.png',
        !          8576:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8577:                         },
1.598   ! www      8578: 
        !          8579:                         {       linktext => 'Grading table',
        !          8580:                                 url => $url1c,
        !          8581:                                 permission => 'F',
        !          8582:                                 icon => 'edit-find-replace.png',
        !          8583:                                 linktitle => 'Grade current resource for all students.'
        !          8584:                         },
        !          8585:                         {       linktext => 'Grade complete page/sequence/folder for one student.',
        !          8586:                                 url => $url1d,
        !          8587:                                 permission => 'F',
        !          8588:                                 icon => 'edit-find-replace.png',
        !          8589:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
        !          8590:                         }]},
        !          8591:                          { categorytitle=>'Automated Grading',
        !          8592:                items =>[
        !          8593: 
1.538     schulted 8594:                 	    {	linktext => 'Upload Scores',
                   8595:                     		url => $url2,
                   8596:                     		permission => 'F',
                   8597:                     		icon => 'uploadscores.png',
                   8598:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8599:                 	    },
                   8600:                 	    {	linktext => 'Process Clicker',
                   8601:                     		url => $url3,
                   8602:                     		permission => 'F',
                   8603:                     		icon => 'addClickerInfoFile.png',
                   8604:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8605:                 	    },
1.587     raeburn  8606:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8607:                     		url => $url4,
                   8608:                     		permission => 'F',
                   8609:                     		icon => 'stat.png',
                   8610:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
                   8611:                 	    }
                   8612:                     ]
                   8613:             });
                   8614: 
                   8615:     #$fields{'command'} = 'verify';
                   8616:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 8617:     #
                   8618:     # Create the menu
                   8619:     my $Str;
1.444     banghart 8620:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8621:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8622:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8623:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.598   ! www      8624: #	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8625: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8626: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8627: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8628: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8629: 
1.538     schulted 8630:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   8631:     #$menudata->{'jscript'}
1.584     bisitz   8632:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   8633:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 8634:         ' /> '.
                   8635:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   8636:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 8637: 
1.444     banghart 8638:     $Str .="</form>\n";
1.539     riegler  8639:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.597     wenzelju 8640:     $request->print(&Apache::lonhtmlcommon::scripttag(<<GRADINGMENUJS));
1.443     banghart 8641:     function checkChoice(formname,val,cmdx) {
                   8642: 	if (val <= 2) {
                   8643: 	    var cmd = radioSelection(formname.radioChoice);
                   8644: 	    var cmdsave = cmd;
                   8645: 	} else {
                   8646: 	    cmd = cmdx;
                   8647: 	    cmdsave = 'submission';
                   8648: 	}
                   8649: 	formname.command.value = cmd;
                   8650: 	if (val < 5) formname.submit();
                   8651: 	if (val == 5) {
1.458     banghart 8652: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8653: 	        return false;
                   8654: 	    } else {
                   8655: 	        formname.submit();
                   8656: 	    }
1.445     banghart 8657: 	}
                   8658:     }
1.443     banghart 8659: 
                   8660:     function checkReceiptNo(formname,nospace) {
                   8661: 	var receiptNo = formname.receipt.value;
                   8662: 	var checkOpt = false;
                   8663: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8664: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8665: 	if (checkOpt) {
1.539     riegler  8666: 	    alert("$receiptalert");
1.443     banghart 8667: 	    formname.receipt.value = "";
                   8668: 	    formname.receipt.focus();
                   8669: 	    return false;
                   8670: 	}
                   8671: 	return true;
                   8672:     }
                   8673: GRADINGMENUJS
                   8674:     &commonJSfunctions($request);
                   8675:     return $Str;    
                   8676: }
                   8677: 
1.598   ! www      8678: sub individual {
        !          8679:     my ($request)=@_;
        !          8680:     &submit_options($request);
        !          8681: }
        !          8682: 
        !          8683: sub ungraded {
        !          8684:     my ($request)=@_;
        !          8685:     &submit_options($request);
        !          8686: }
        !          8687: 
        !          8688: sub table {
        !          8689:     my ($request)=@_;
        !          8690:     &submit_options($request);
        !          8691: }
        !          8692: 
        !          8693: sub all_for_one {
        !          8694:     my ($request)=@_;
        !          8695:     &submit_options($request);
        !          8696: }
        !          8697: 
1.443     banghart 8698: 
                   8699: #--- Displays the submissions first page -------
                   8700: sub submit_options {
1.72      ng       8701:     my ($request) = @_;
1.324     albertel 8702:     my ($symb)=&get_symb($request);
1.72      ng       8703:     if (!$symb) {return '';}
1.76      ng       8704:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8705: 
1.539     riegler  8706:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.597     wenzelju 8707:     $request->print(&Apache::lonhtmlcommon::scripttag(<<GRADINGMENUJS));
1.116     ng       8708:     function checkChoice(formname,val,cmdx) {
                   8709: 	if (val <= 2) {
                   8710: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8711: 	    var cmdsave = cmd;
1.116     ng       8712: 	} else {
                   8713: 	    cmd = cmdx;
1.118     ng       8714: 	    cmdsave = 'submission';
1.116     ng       8715: 	}
                   8716: 	formname.command.value = cmd;
1.118     ng       8717: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8718: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8719: 	if (val < 5) formname.submit();
                   8720: 	if (val == 5) {
1.72      ng       8721: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8722: 	    formname.submit();
                   8723: 	}
1.238     albertel 8724: 	if (val < 7) formname.submit();
1.72      ng       8725:     }
                   8726: 
                   8727:     function checkReceiptNo(formname,nospace) {
                   8728: 	var receiptNo = formname.receipt.value;
                   8729: 	var checkOpt = false;
                   8730: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8731: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8732: 	if (checkOpt) {
1.539     riegler  8733: 	    alert("$receiptalert");
1.72      ng       8734: 	    formname.receipt.value = "";
                   8735: 	    formname.receipt.focus();
                   8736: 	    return false;
                   8737: 	}
                   8738: 	return true;
                   8739:     }
                   8740: GRADINGMENUJS
1.118     ng       8741:     &commonJSfunctions($request);
1.598   ! www      8742: #    my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8743:     my $result;
1.76      ng       8744:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8745:     my $savedState = &savedState();
1.118     ng       8746:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8747:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8748:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8749:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8750: 
1.533     bisitz   8751:     # Preselect sections
                   8752:     my $selsec="";
                   8753:     if (ref($sections)) {
                   8754:         foreach my $section (sort(@$sections)) {
                   8755:             $selsec.='<option value="'.$section.'" '.
                   8756:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8757:         }
                   8758:     }
                   8759: 
1.72      ng       8760:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8761: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.598   ! www      8762: #	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.72      ng       8763: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8764: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8765: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8766: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8767: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8768: 
1.472     albertel 8769:     $result.='
1.533     bisitz   8770: <h2>
                   8771:   '.&mt('Grade Current Resource').'
                   8772: </h2>
                   8773: 
1.537     harmsja  8774: <div class="LC_columnSection">
                   8775:   
1.533     bisitz   8776:     <fieldset>
                   8777:       <legend>
                   8778:        '.&mt('Sections').'
                   8779:       </legend>
                   8780:       <select name="section" multiple="multiple" size="5">'."\n";
                   8781:     $result.= $selsec;
1.401     albertel 8782:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8783:     $result.='
1.533     bisitz   8784:     </fieldset>
1.537     harmsja  8785:   
1.533     bisitz   8786:     <fieldset>
                   8787:       <legend>
                   8788:         '.&mt('Groups').'
                   8789:       </legend>
                   8790:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8791:     </fieldset>
1.537     harmsja  8792:   
1.533     bisitz   8793:     <fieldset>
                   8794:       <legend>
                   8795:         '.&mt('Access Status').'
                   8796:       </legend>
                   8797:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8798:     </fieldset>
1.537     harmsja  8799:   
1.533     bisitz   8800:     <fieldset>
                   8801:       <legend>
                   8802:         '.&mt('Submission Status').'
                   8803:       </legend>
                   8804:       <select name="submitonly" size="5">
1.473     albertel 8805: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8806: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8807: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8808: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8809:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   8810:       </select>
                   8811:     </fieldset>
1.537     harmsja  8812:   
1.533     bisitz   8813: </div>
                   8814: 
                   8815: <br />
                   8816:           <div>
                   8817:             <div>
1.473     albertel 8818:               <label>
                   8819:                 <input type="radio" name="radioChoice" value="submission" '.
                   8820:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8821:              &mt('Select individual students to grade and view submissions.').'
                   8822: 	      </label> 
                   8823:             </div>
1.533     bisitz   8824:             <div>
1.473     albertel 8825: 	      <label>
                   8826:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8827:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8828:                     &mt('Grade all selected students in a grading table.').'
                   8829:               </label>
                   8830:             </div>
1.533     bisitz   8831:             <div>
1.589     bisitz   8832: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8833:             </div>
1.472     albertel 8834:           </div>
1.533     bisitz   8835: 
                   8836: 
1.473     albertel 8837:         <h2>
                   8838:          '.&mt('Grade Complete Folder for One Student').'
                   8839:         </h2>
1.533     bisitz   8840:         <div>
                   8841:             <div>
1.473     albertel 8842:               <label>
                   8843:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8844: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8845:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8846:               </label>
                   8847:             </div>
1.533     bisitz   8848:             <div>
1.589     bisitz   8849: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8850:             </div>
1.472     albertel 8851:         </div>
                   8852:   </form>';
1.499     albertel 8853:     $result .= &show_grading_menu_form($symb);
1.44      ng       8854:     return $result;
1.2       albertel 8855: }
                   8856: 
1.285     albertel 8857: sub reset_perm {
                   8858:     undef(%perm);
                   8859: }
                   8860: 
                   8861: sub init_perm {
                   8862:     &reset_perm();
1.300     albertel 8863:     foreach my $test_perm ('vgr','mgr','opa') {
                   8864: 
                   8865: 	my $scope = $env{'request.course.id'};
                   8866: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8867: 
                   8868: 	    $scope .= '/'.$env{'request.course.sec'};
                   8869: 	    if ( $perm{$test_perm}=
                   8870: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8871: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8872: 	    } else {
                   8873: 		delete($perm{$test_perm});
                   8874: 	    }
1.285     albertel 8875: 	}
                   8876:     }
                   8877: }
                   8878: 
1.400     www      8879: sub gather_clicker_ids {
1.408     albertel 8880:     my %clicker_ids;
1.400     www      8881: 
                   8882:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8883: 
                   8884:     # Set up a couple variables.
1.407     albertel 8885:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8886:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8887:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8888: 
1.407     albertel 8889:     foreach my $student (keys(%$classlist)) {
1.438     www      8890:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8891:         my $username = $classlist->{$student}->[$username_idx];
                   8892:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8893:         my $clickers =
1.408     albertel 8894: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8895:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8896:             $id=~s/^[\#0]+//;
1.421     www      8897:             $id=~s/[\-\:]//g;
1.407     albertel 8898:             if (exists($clicker_ids{$id})) {
1.408     albertel 8899: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8900:             } else {
1.408     albertel 8901: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8902:             }
                   8903:         }
                   8904:     }
1.407     albertel 8905:     return %clicker_ids;
1.400     www      8906: }
                   8907: 
1.402     www      8908: sub gather_adv_clicker_ids {
1.408     albertel 8909:     my %clicker_ids;
1.402     www      8910:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8911:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8912:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8913:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8914:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8915:             my ($puname,$pudom)=split(/\:/,$person);
                   8916:             my $clickers =
1.408     albertel 8917: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8918:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8919: 		$id=~s/^[\#0]+//;
1.421     www      8920:                 $id=~s/[\-\:]//g;
1.408     albertel 8921: 		if (exists($clicker_ids{$id})) {
                   8922: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8923: 		} else {
                   8924: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8925: 		}
1.405     www      8926:             }
1.402     www      8927:         }
                   8928:     }
1.407     albertel 8929:     return %clicker_ids;
1.402     www      8930: }
                   8931: 
1.413     www      8932: sub clicker_grading_parameters {
                   8933:     return ('gradingmechanism' => 'scalar',
                   8934:             'upfiletype' => 'scalar',
                   8935:             'specificid' => 'scalar',
                   8936:             'pcorrect' => 'scalar',
                   8937:             'pincorrect' => 'scalar');
                   8938: }
                   8939: 
1.400     www      8940: sub process_clicker {
                   8941:     my ($r)=@_;
                   8942:     my ($symb)=&get_symb($r);
                   8943:     if (!$symb) {return '';}
                   8944:     my $result=&checkforfile_js();
                   8945:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.598   ! www      8946: #    my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
        !          8947: #    $result.=$table;
1.400     www      8948:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8949:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8950:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8951:         '</b></td></tr>'."\n";
1.400     www      8952:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8953: # Attempt to restore parameters from last session, set defaults if not present
                   8954:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8955:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8956:                                                  \%Saveable_Parameters);
                   8957:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8958:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8959:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8960:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8961: 
                   8962:     my %checked;
1.521     www      8963:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8964:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8965:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8966:        }
                   8967:     }
                   8968: 
1.400     www      8969:     my $upload=&mt("Upload File");
                   8970:     my $type=&mt("Type");
1.402     www      8971:     my $attendance=&mt("Award points just for participation");
                   8972:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8973:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8974:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8975:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8976:     my $pcorrect=&mt("Percentage points for correct solution");
                   8977:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8978:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8979: 						   ('iclicker' => 'i>clicker',
                   8980:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8981:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8982:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8983: function sanitycheck() {
                   8984: // Accept only integer percentages
                   8985:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8986:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8987: // Find out grading choice
                   8988:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8989:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8990:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8991:       }
                   8992:    }
                   8993: // By default, new choice equals user selection
                   8994:    newgradingchoice=gradingchoice;
                   8995: // Not good to give more points for false answers than correct ones
                   8996:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8997:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8998:    }
                   8999: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9000:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9001:       document.forms.gradesupload.pcorrect.value=100;
                   9002:       document.forms.gradesupload.pincorrect.value=100;
                   9003:    }
                   9004: // If the values are different, cannot be attendance only
                   9005:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9006:        (gradingchoice=='attendance')) {
                   9007:        newgradingchoice='personnel';
                   9008:    }
                   9009: // Change grading choice to new one
                   9010:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9011:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9012:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9013:       } else {
                   9014:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9015:       }
                   9016:    }
                   9017: // Remember the old state
                   9018:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9019: }
1.597     wenzelju 9020: ENDUPFORM
                   9021:     $result.= <<ENDUPFORM;
1.400     www      9022: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9023: <input type="hidden" name="symb" value="$symb" />
                   9024: <input type="hidden" name="command" value="processclickerfile" />
                   9025: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9026: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   9027: <input type="file" name="upfile" size="50" />
                   9028: <br /><label>$type: $selectform</label>
1.589     bisitz   9029: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   9030: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9031: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9032: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9033: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9034: <br />&nbsp;&nbsp;&nbsp;
                   9035: <input type="text" name="givenanswer" size="50" />
1.413     www      9036: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   9037: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   9038: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9039: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9040: </form>'
1.400     www      9041: ENDUPFORM
                   9042:     $result.='</td></tr></table>'."\n".
                   9043:              '</td></tr></table><br /><br />'."\n";
                   9044:     $result.=&show_grading_menu_form($symb);
                   9045:     return $result;
                   9046: }
                   9047: 
                   9048: sub process_clicker_file {
                   9049:     my ($r)=@_;
                   9050:     my ($symb)=&get_symb($r);
                   9051:     if (!$symb) {return '';}
1.413     www      9052: 
                   9053:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9054:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9055:                                               \%Saveable_Parameters);
1.598   ! www      9056:     my $result='';
        !          9057: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      9058:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9059: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   9060: 	return $result.&show_grading_menu_form($symb);
1.404     www      9061:     }
1.522     www      9062:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9063:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   9064:         return $result.&show_grading_menu_form($symb);
                   9065:     }
1.522     www      9066:     my $foundgiven=0;
1.521     www      9067:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9068:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9069:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   9070:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   9071:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9072:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9073:         $foundgiven=$#answers+1;
1.521     www      9074:     }
1.407     albertel 9075:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9076:     my %correct_ids;
1.404     www      9077:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9078: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9079:     }
                   9080:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9081: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9082: 	   $correct_id=~tr/a-z/A-Z/;
                   9083: 	   $correct_id=~s/\s//gs;
                   9084: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9085:            $correct_id=~s/[\-\:]//g;
1.414     www      9086:            if ($correct_id) {
                   9087: 	      $correct_ids{$correct_id}='specified';
                   9088:            }
                   9089:         }
1.400     www      9090:     }
1.404     www      9091:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9092: 	$result.=&mt('Score based on attendance only');
1.521     www      9093:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9094:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9095:     } else {
1.408     albertel 9096: 	my $number=0;
1.411     www      9097: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9098: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9099: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9100: 	    if ($correct_ids{$id} eq 'specified') {
                   9101: 		$result.=&mt('specified');
                   9102: 	    } else {
                   9103: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9104: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9105: 	    }
                   9106: 	    $number++;
                   9107: 	}
1.411     www      9108:         $result.="</p>\n";
1.408     albertel 9109: 	if ($number==0) {
                   9110: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   9111: 	    return $result.&show_grading_menu_form($symb);
                   9112: 	}
1.404     www      9113:     }
1.405     www      9114:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 9115:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   9116: 		     '<span class="LC_error">',
                   9117: 		     '</span>',
                   9118: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      9119:         return $result.&show_grading_menu_form($symb);
                   9120:     }
1.410     www      9121: 
                   9122: # Were able to get all the info needed, now analyze the file
                   9123: 
1.411     www      9124:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9125:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      9126:     my $heading=&mt('Scanning clicker file');
                   9127:     $result.=(<<ENDHEADER);
                   9128: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9129: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9130: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9131: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9132: <input type="hidden" name="symb" value="$symb" />
                   9133: <input type="hidden" name="command" value="assignclickergrades" />
                   9134: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9135: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      9136: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9137: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9138: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9139: ENDHEADER
1.522     www      9140:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9141:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9142:     } 
1.408     albertel 9143:     my %responses;
                   9144:     my @questiontitles;
1.405     www      9145:     my $errormsg='';
                   9146:     my $number=0;
                   9147:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9148: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9149:     }
1.419     www      9150:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9151:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9152:     }
1.411     www      9153:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9154:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9155:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9156:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9157:              '<br />';
1.522     www      9158:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9159:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9160:        return $result.&show_grading_menu_form($symb);
                   9161:     } 
1.414     www      9162: # Remember Question Titles
                   9163: # FIXME: Possibly need delimiter other than ":"
                   9164:     for (my $i=0;$i<$number;$i++) {
                   9165:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9166:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9167:     }
1.411     www      9168:     my $correct_count=0;
                   9169:     my $student_count=0;
                   9170:     my $unknown_count=0;
1.414     www      9171: # Match answers with usernames
                   9172: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9173:     foreach my $id (keys(%responses)) {
1.410     www      9174:        if ($correct_ids{$id}) {
1.414     www      9175:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9176:           $correct_count++;
1.410     www      9177:        } elsif ($clicker_ids{$id}) {
1.437     www      9178:           if ($clicker_ids{$id}=~/\,/) {
                   9179: # More than one user with the same clicker!
                   9180:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9181:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9182:                            "<select name='multi".$id."'>";
                   9183:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9184:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9185:              }
                   9186:              $result.='</select>';
                   9187:              $unknown_count++;
                   9188:           } else {
                   9189: # Good: found one and only one user with the right clicker
                   9190:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9191:              $student_count++;
                   9192:           }
1.410     www      9193:        } else {
1.411     www      9194:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9195:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9196:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9197:                    "\n".&mt("Domain").": ".
                   9198:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   9199:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   9200:           $unknown_count++;
1.410     www      9201:        }
1.405     www      9202:     }
1.412     www      9203:     $result.='<hr />'.
                   9204:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9205:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9206:        if ($correct_count==0) {
                   9207:           $errormsg.="Found no correct answers answers for grading!";
                   9208:        } elsif ($correct_count>1) {
1.414     www      9209:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9210:        }
                   9211:     }
1.428     www      9212:     if ($number<1) {
                   9213:        $errormsg.="Found no questions.";
                   9214:     }
1.412     www      9215:     if ($errormsg) {
                   9216:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9217:     } else {
                   9218:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9219:     }
                   9220:     $result.='</form></td></tr></table>'."\n".
1.410     www      9221:              '</td></tr></table><br /><br />'."\n";
1.404     www      9222:     return $result.&show_grading_menu_form($symb);
1.400     www      9223: }
                   9224: 
1.405     www      9225: sub iclicker_eval {
1.406     www      9226:     my ($questiontitles,$responses)=@_;
1.405     www      9227:     my $number=0;
                   9228:     my $errormsg='';
                   9229:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9230:         my %components=&Apache::loncommon::record_sep($line);
                   9231:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9232: 	if ($entries[0] eq 'Question') {
                   9233: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9234: 		$$questiontitles[$number]=$entries[$i];
                   9235: 		$number++;
                   9236: 	    }
                   9237: 	}
                   9238: 	if ($entries[0]=~/^\#/) {
                   9239: 	    my $id=$entries[0];
                   9240: 	    my @idresponses;
                   9241: 	    $id=~s/^[\#0]+//;
                   9242: 	    for (my $i=0;$i<$number;$i++) {
                   9243: 		my $idx=3+$i*6;
                   9244: 		push(@idresponses,$entries[$idx]);
                   9245: 	    }
                   9246: 	    $$responses{$id}=join(',',@idresponses);
                   9247: 	}
1.405     www      9248:     }
                   9249:     return ($errormsg,$number);
                   9250: }
                   9251: 
1.419     www      9252: sub interwrite_eval {
                   9253:     my ($questiontitles,$responses)=@_;
                   9254:     my $number=0;
                   9255:     my $errormsg='';
1.420     www      9256:     my $skipline=1;
                   9257:     my $questionnumber=0;
                   9258:     my %idresponses=();
1.419     www      9259:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9260:         my %components=&Apache::loncommon::record_sep($line);
                   9261:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9262:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9263:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9264:         next if $skipline;
                   9265:         if ($entries[0]!=$questionnumber) {
                   9266:            $questionnumber=$entries[0];
                   9267:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9268:            $number++;
1.419     www      9269:         }
1.420     www      9270:         my $id=$entries[4];
                   9271:         $id=~s/^[\#0]+//;
1.421     www      9272:         $id=~s/^v\d*\://i;
                   9273:         $id=~s/[\-\:]//g;
1.420     www      9274:         $idresponses{$id}[$number]=$entries[6];
                   9275:     }
1.524     raeburn  9276:     foreach my $id (keys(%idresponses)) {
1.420     www      9277:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9278:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9279:     }
                   9280:     return ($errormsg,$number);
                   9281: }
                   9282: 
1.414     www      9283: sub assign_clicker_grades {
                   9284:     my ($r)=@_;
                   9285:     my ($symb)=&get_symb($r);
                   9286:     if (!$symb) {return '';}
1.416     www      9287: # See which part we are saving to
1.582     raeburn  9288:     my $res_error;
                   9289:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9290:     if ($res_error) {
                   9291:         return &navmap_errormsg();
                   9292:     }
1.416     www      9293: # FIXME: This should probably look for the first handgradeable part
                   9294:     my $part=$$partlist[0];
                   9295: # Start screen output
1.598   ! www      9296:     my $result='';
        !          9297: #    my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      9298: 
1.414     www      9299:     my $heading=&mt('Assigning grades based on clicker file');
                   9300:     $result.=(<<ENDHEADER);
                   9301: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9302: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9303: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9304: ENDHEADER
                   9305: # Get correct result
                   9306: # FIXME: Possibly need delimiter other than ":"
                   9307:     my @correct=();
1.415     www      9308:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9309:     my $number=$env{'form.number'};
                   9310:     if ($gradingmechanism ne 'attendance') {
1.414     www      9311:        foreach my $key (keys(%env)) {
                   9312:           if ($key=~/^form\.correct\:/) {
                   9313:              my @input=split(/\,/,$env{$key});
                   9314:              for (my $i=0;$i<=$#input;$i++) {
                   9315:                  if (($correct[$i]) && ($input[$i]) &&
                   9316:                      ($correct[$i] ne $input[$i])) {
                   9317:                     $result.='<br /><span class="LC_warning">'.
                   9318:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9319:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9320:                  } elsif ($input[$i]) {
                   9321:                     $correct[$i]=$input[$i];
                   9322:                  }
                   9323:              }
                   9324:           }
                   9325:        }
1.415     www      9326:        for (my $i=0;$i<$number;$i++) {
1.414     www      9327:           if (!$correct[$i]) {
                   9328:              $result.='<br /><span class="LC_error">'.
                   9329:                       &mt('No correct result given for question "[_1]"!',
                   9330:                           $env{'form.question:'.$i}).'</span>';
                   9331:           }
                   9332:        }
                   9333:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9334:     }
                   9335: # Start grading
1.415     www      9336:     my $pcorrect=$env{'form.pcorrect'};
                   9337:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9338:     my $storecount=0;
1.415     www      9339:     foreach my $key (keys(%env)) {
1.420     www      9340:        my $user='';
1.415     www      9341:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9342:           $user=$1;
                   9343:        }
                   9344:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9345:           my $id=$1;
                   9346:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9347:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9348:           } elsif ($env{'form.multi'.$id}) {
                   9349:              $user=$env{'form.multi'.$id};
1.420     www      9350:           }
                   9351:        }
                   9352:        if ($user) { 
1.415     www      9353:           my @answer=split(/\,/,$env{$key});
                   9354:           my $sum=0;
1.522     www      9355:           my $realnumber=$number;
1.415     www      9356:           for (my $i=0;$i<$number;$i++) {
1.576     www      9357:              if  ($correct[$i] eq '-') {
                   9358:                 $realnumber--;
                   9359:              } elsif ($answer[$i]) {
1.415     www      9360:                 if ($gradingmechanism eq 'attendance') {
                   9361:                    $sum+=$pcorrect;
1.576     www      9362:                 } elsif ($correct[$i] eq '*') {
1.522     www      9363:                    $sum+=$pcorrect;
1.415     www      9364:                 } else {
                   9365:                    if ($answer[$i] eq $correct[$i]) {
                   9366:                       $sum+=$pcorrect;
                   9367:                    } else {
                   9368:                       $sum+=$pincorrect;
                   9369:                    }
                   9370:                 }
                   9371:              }
                   9372:           }
1.522     www      9373:           my $ave=$sum/(100*$realnumber);
1.416     www      9374: # Store
                   9375:           my ($username,$domain)=split(/\:/,$user);
                   9376:           my %grades=();
                   9377:           $grades{"resource.$part.solved"}='correct_by_override';
                   9378:           $grades{"resource.$part.awarded"}=$ave;
                   9379:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9380:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9381:                                                  $env{'request.course.id'},
                   9382:                                                  $domain,$username);
                   9383:           if ($returncode ne 'ok') {
                   9384:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9385:           } else {
                   9386:              $storecount++;
                   9387:           }
1.415     www      9388:        }
                   9389:     }
                   9390: # We are done
1.549     hauer    9391:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9392:              '</td></tr></table>'."\n".
1.414     www      9393:              '</td></tr></table><br /><br />'."\n";
                   9394:     return $result.&show_grading_menu_form($symb);
                   9395: }
                   9396: 
1.582     raeburn  9397: sub navmap_errormsg {
                   9398:     return '<div class="LC_error">'.
                   9399:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9400:            &mt('It is recommended that you [_1]re-initialize the course[_2] and then return to this grading page.','<a href="/adm/roles?selectrole=1&newrole='.$env{'request.role'}.'">','</a>').
1.582     raeburn  9401:            '</div>';
                   9402: }
                   9403: 
1.1       albertel 9404: sub handler {
1.41      ng       9405:     my $request=$_[0];
1.434     albertel 9406:     &reset_caches();
1.257     albertel 9407:     if ($env{'browser.mathml'}) {
1.141     www      9408: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9409:     } else {
1.141     www      9410: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9411:     }
                   9412:     $request->send_http_header;
1.44      ng       9413:     return '' if $request->header_only;
1.41      ng       9414:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9415:     my $symb=&get_symb($request,1);
1.160     albertel 9416:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9417:     my $command=$commands[0];
1.447     foxr     9418: 
1.160     albertel 9419:     if ($#commands > 0) {
                   9420: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9421:     }
1.447     foxr     9422: 
1.513     foxr     9423:     $ssi_error = 0;
1.535     raeburn  9424:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9425:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9426:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9427:     if ($symb eq '' && $command eq '') {
1.257     albertel 9428: 	if ($env{'user.adv'}) {
                   9429: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9430: 		($env{'form.codethree'})) {
                   9431: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9432: 		    $env{'form.codethree'};
1.41      ng       9433: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9434: 		    &Apache::lonnet::checkin($token);
                   9435: 		if ($tsymb) {
1.137     albertel 9436: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9437: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9438: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9439: 					  ('grade_username' => $tuname,
                   9440: 					   'grade_domain' => $tudom,
                   9441: 					   'grade_courseid' => $tcrsid,
                   9442: 					   'grade_symb' => $tsymb)));
1.41      ng       9443: 		    } else {
1.45      ng       9444: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9445: 		    }
1.41      ng       9446: 		} else {
1.45      ng       9447: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9448: 		}
1.14      www      9449: 	    } else {
1.41      ng       9450: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9451: 	    }
                   9452: 	}
                   9453:     } else {
1.285     albertel 9454: 	&init_perm();
1.104     albertel 9455: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9456: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9457: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9458: 	    &pickStudentPage($request);
1.103     albertel 9459: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9460: 	    &displayPage($request);
1.104     albertel 9461: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9462: 	    &updateGradeByPage($request);
1.104     albertel 9463: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9464: 	    &processGroup($request);
1.104     albertel 9465: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9466: 	    $request->print(&grading_menu($request));
1.598   ! www      9467: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
        !          9468: 	    $request->print(&individual($request));
        !          9469:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
        !          9470:             $request->print(&submit_options($request));
        !          9471:         } elsif ($command eq 'table' && $perm{'vgr'}) {
        !          9472:             $request->print(&submit_options($request));
        !          9473:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
        !          9474:             $request->print(&submit_options($request));
1.104     albertel 9475: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9476: 	    $request->print(&viewgrades($request));
1.104     albertel 9477: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9478: 	    $request->print(&processHandGrade($request));
1.106     albertel 9479: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9480: 	    $request->print(&editgrades($request));
1.106     albertel 9481: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9482: 	    $request->print(&verifyreceipt($request));
1.400     www      9483:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9484:             $request->print(&process_clicker($request));
                   9485:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9486:             $request->print(&process_clicker_file($request));
1.414     www      9487:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9488:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9489: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9490: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9491: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9492: 	    $request->print(&csvupload($request));
1.106     albertel 9493: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9494: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9495: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9496: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9497: 		$request->print(&csvuploadoptions($request));
1.41      ng       9498: 	    } else {
1.257     albertel 9499: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9500: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9501: 		} else {
1.257     albertel 9502: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9503: 		}
                   9504: 		$request->print(&csvuploadmap($request));
                   9505: 	    }
1.246     albertel 9506: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9507: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9508: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9509: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9510:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9511:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9512: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9513: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9514: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9515: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9516:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9517:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9518: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9519:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9520:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9521:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9522: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9523:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9524:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9525: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9526:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9527:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9528:             $request->print(&checkscantron_results($request));     
1.106     albertel 9529: 	} elsif ($command) {
1.562     bisitz   9530: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9531: 	}
1.2       albertel 9532:     }
1.513     foxr     9533:     if ($ssi_error) {
                   9534: 	&ssi_print_error($request);
                   9535:     }
1.353     albertel 9536:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9537:     &reset_caches();
1.44      ng       9538:     return '';
                   9539: }
                   9540: 
1.1       albertel 9541: 1;
                   9542: 
1.13      albertel 9543: __END__;
1.531     jms      9544: 
                   9545: 
                   9546: =head1 NAME
                   9547: 
                   9548: Apache::grades
                   9549: 
                   9550: =head1 SYNOPSIS
                   9551: 
                   9552: Handles the viewing of grades.
                   9553: 
                   9554: This is part of the LearningOnline Network with CAPA project
                   9555: described at http://www.lon-capa.org.
                   9556: 
                   9557: =head1 OVERVIEW
                   9558: 
                   9559: Do an ssi with retries:
                   9560: While I'd love to factor out this with the vesrion in lonprintout,
                   9561: that would either require a data coupling between modules, which I refuse to perpetuate (there's quite enough of that already), or would require the invention of another infrastructure
                   9562: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9563: 
                   9564: At least the logic that drives this has been pulled out into loncommon.
                   9565: 
                   9566: 
                   9567: 
                   9568: ssi_with_retries - Does the server side include of a resource.
                   9569:                      if the ssi call returns an error we'll retry it up to
                   9570:                      the number of times requested by the caller.
                   9571:                      If we still have a proble, no text is appended to the
                   9572:                      output and we set some global variables.
                   9573:                      to indicate to the caller an SSI error occurred.  
                   9574:                      All of this is supposed to deal with the issues described
                   9575:                      in LonCAPA BZ 5631 see:
                   9576:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9577:                      by informing the user that this happened.
                   9578: 
                   9579: Parameters:
                   9580:   resource   - The resource to include.  This is passed directly, without
                   9581:                interpretation to lonnet::ssi.
                   9582:   form       - The form hash parameters that guide the interpretation of the resource
                   9583:                
                   9584:   retries    - Number of retries allowed before giving up completely.
                   9585: Returns:
                   9586:   On success, returns the rendered resource identified by the resource parameter.
                   9587: Side Effects:
                   9588:   The following global variables can be set:
                   9589:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9590:                               It is up to the caller to initialize this to false
                   9591:                               if desired.
                   9592:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9593:                               of the resource that could not be rendered by the ssi
                   9594:                               call.
                   9595:    ssi_error_message   - The error string fetched from the ssi response
                   9596:                               in the event of an error.
                   9597: 
                   9598: 
                   9599: =head1 HANDLER SUBROUTINE
                   9600: 
                   9601: ssi_with_retries()
                   9602: 
                   9603: =head1 SUBROUTINES
                   9604: 
                   9605: =over
                   9606: 
                   9607: =item scantron_get_correction() : 
                   9608: 
                   9609:    Builds the interface screen to interact with the operator to fix a
                   9610:    specific error condition in a specific scanline
                   9611: 
                   9612:  Arguments:
                   9613:     $r           - Apache request object
                   9614:     $i           - number of the current scanline
                   9615:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9616:     $scan_config - hash ref as returned from &get_scantron_config()
                   9617:     $line        - full contents of the current scanline
                   9618:     $error       - error condition, valid values are
                   9619:                    'incorrectCODE', 'duplicateCODE',
                   9620:                    'doublebubble', 'missingbubble',
                   9621:                    'duplicateID', 'incorrectID'
                   9622:     $arg         - extra information needed
                   9623:        For errors:
                   9624:          - duplicateID   - paper number that this studentID was seen before on
                   9625:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9626:                            seen on before
                   9627:          - incorrectCODE - current incorrect CODE 
                   9628:          - doublebubble  - array ref of the bubble lines that have double
                   9629:                            bubble errors
                   9630:          - missingbubble - array ref of the bubble lines that have missing
                   9631:                            bubble errors
                   9632: 
                   9633: =item  scantron_get_maxbubble() : 
                   9634: 
1.582     raeburn  9635:    Arguments:
                   9636:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9637:                       failure to retrieve a navmap object.
                   9638:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9639:        calling routine should trap the error condition and display the warning
                   9640:        found in &navmap_errormsg().
                   9641: 
1.531     jms      9642:    Returns the maximum number of bubble lines that are expected to
                   9643:    occur. Does this by walking the selected sequence rendering the
                   9644:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9645:    for what the current value of the problem counter is.
                   9646: 
                   9647:    Caches the results to $env{'form.scantron_maxbubble'},
                   9648:    $env{'form.scantron.bubble_lines.n'}, 
                   9649:    $env{'form.scantron.first_bubble_line.n'} and
                   9650:    $env{"form.scantron.sub_bubblelines.n"}
                   9651:    which are the total number of bubble, lines, the number of bubble
                   9652:    lines for response n and number of the first bubble line for response n,
                   9653:    and a comma separated list of numbers of bubble lines for sub-questions
                   9654:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9655: 
                   9656: 
                   9657: =item  scantron_validate_missingbubbles() : 
                   9658: 
                   9659:    Validates all scanlines in the selected file to not have any
                   9660:     answers that don't have bubbles that have not been verified
                   9661:     to be bubble free.
                   9662: 
                   9663: =item  scantron_process_students() : 
                   9664: 
                   9665:    Routine that does the actual grading of the bubble sheet information.
                   9666: 
                   9667:    The parsed scanline hash is added to %env 
                   9668: 
                   9669:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9670:    foreach resource , with the form data of
                   9671: 
                   9672: 	'submitted'     =>'scantron' 
                   9673: 	'grade_target'  =>'grade',
                   9674: 	'grade_username'=> username of student
                   9675: 	'grade_domain'  => domain of student
                   9676: 	'grade_courseid'=> of course
                   9677: 	'grade_symb'    => symb of resource to grade
                   9678: 
                   9679:     This triggers a grading pass. The problem grading code takes care
                   9680:     of converting the bubbled letter information (now in %env) into a
                   9681:     valid submission.
                   9682: 
                   9683: =item  scantron_upload_scantron_data() :
                   9684: 
                   9685:     Creates the screen for adding a new bubble sheet data file to a course.
                   9686: 
                   9687: =item  scantron_upload_scantron_data_save() : 
                   9688: 
                   9689:    Adds a provided bubble information data file to the course if user
                   9690:    has the correct privileges to do so. 
                   9691: 
                   9692: =item  valid_file() :
                   9693: 
                   9694:    Validates that the requested bubble data file exists in the course.
                   9695: 
                   9696: =item  scantron_download_scantron_data() : 
                   9697: 
                   9698:    Shows a list of the three internal files (original, corrected,
                   9699:    skipped) for a specific bubble sheet data file that exists in the
                   9700:    course.
                   9701: 
                   9702: =item  scantron_validate_ID() : 
                   9703: 
                   9704:    Validates all scanlines in the selected file to not have any
1.556     weissno  9705:    invalid or underspecified student/employee IDs
1.531     jms      9706: 
1.582     raeburn  9707: =item navmap_errormsg() :
                   9708: 
                   9709:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9710:    Should be called whenever the request to instantiate a navmap object fails.  
                   9711: 
1.531     jms      9712: =back
                   9713: 
                   9714: =cut

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