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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.529   ! jms         4: # $Id: grades.pm,v 1.528 2008/07/14 10:28:19 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529   ! jms        29: =head1 NAME
        !            30: 
        !            31: Apache::grades
        !            32: 
        !            33: =head1 SYNOPSIS
        !            34: 
        !            35: Handles the viewing of grades.
        !            36: 
        !            37: This is part of the LearningOnline Network with CAPA project
        !            38: described at http://www.lon-capa.org.
        !            39: 
        !            40: =head1 OVERVIEW
        !            41: 
        !            42: Do an ssi with retries:
        !            43: While I'd love to factor out this with the vesrion in lonprintout,
        !            44: 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
        !            45: I'm not quite ready to invent (e.g. an ssi_with_retry object).
        !            46: 
        !            47: At least the logic that drives this has been pulled out into loncommon.
        !            48: 
        !            49: 
        !            50: 
        !            51: ssi_with_retries - Does the server side include of a resource.
        !            52:                      if the ssi call returns an error we'll retry it up to
        !            53:                      the number of times requested by the caller.
        !            54:                      If we still have a proble, no text is appended to the
        !            55:                      output and we set some global variables.
        !            56:                      to indicate to the caller an SSI error occurred.  
        !            57:                      All of this is supposed to deal with the issues described
        !            58:                      in LonCAPA BZ 5631 see:
        !            59:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
        !            60:                      by informing the user that this happened.
        !            61: 
        !            62: Parameters:
        !            63:   resource   - The resource to include.  This is passed directly, without
        !            64:                interpretation to lonnet::ssi.
        !            65:   form       - The form hash parameters that guide the interpretation of the resource
        !            66:                
        !            67:   retries    - Number of retries allowed before giving up completely.
        !            68: Returns:
        !            69:   On success, returns the rendered resource identified by the resource parameter.
        !            70: Side Effects:
        !            71:   The following global variables can be set:
        !            72:    ssi_error                - If an unrecoverable error occurred this becomes true.
        !            73:                               It is up to the caller to initialize this to false
        !            74:                               if desired.
        !            75:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
        !            76:                               of the resource that could not be rendered by the ssi
        !            77:                               call.
        !            78:    ssi_error_message   - The error string fetched from the ssi response
        !            79:                               in the event of an error.
        !            80: 
        !            81: 
        !            82: =head1 HANDLER SUBROUTINE
        !            83: 
        !            84: ssi_with_retries()
        !            85: 
        !            86: =head1 OTHER SUBROUTINES
        !            87: 
        !            88: =over
        !            89: 
        !            90: =item *
        !            91: 
        !            92: 
        !            93: scantron_get_correction() : 
        !            94: 
        !            95:    Builds the interface screen to interact with the operator to fix a
        !            96:    specific error condition in a specific scanline
        !            97: 
        !            98:  Arguments:
        !            99:     $r           - Apache request object
        !           100:     $i           - number of the current scanline
        !           101:     $scan_record - hash ref as returned from &scantron_parse_scanline()
        !           102:     $scan_config - hash ref as returned from &get_scantron_config()
        !           103:     $line        - full contents of the current scanline
        !           104:     $error       - error condition, valid values are
        !           105:                    'incorrectCODE', 'duplicateCODE',
        !           106:                    'doublebubble', 'missingbubble',
        !           107:                    'duplicateID', 'incorrectID'
        !           108:     $arg         - extra information needed
        !           109:        For errors:
        !           110:          - duplicateID   - paper number that this studentID was seen before on
        !           111:          - duplicateCODE - array ref of the paper numbers this CODE was
        !           112:                            seen on before
        !           113:          - incorrectCODE - current incorrect CODE 
        !           114:          - doublebubble  - array ref of the bubble lines that have double
        !           115:                            bubble errors
        !           116:          - missingbubble - array ref of the bubble lines that have missing
        !           117:                            bubble errors
        !           118: 
        !           119: =item *
        !           120: 
        !           121: scantron_get_maxbubble() : 
        !           122: 
        !           123:    Returns the maximum number of bubble lines that are expected to
        !           124:    occur. Does this by walking the selected sequence rendering the
        !           125:    resource and then checking &Apache::lonxml::get_problem_counter()
        !           126:    for what the current value of the problem counter is.
        !           127: 
        !           128:    Caches the results to $env{'form.scantron_maxbubble'},
        !           129:    $env{'form.scantron.bubble_lines.n'}, 
        !           130:    $env{'form.scantron.first_bubble_line.n'} and
        !           131:    $env{"form.scantron.sub_bubblelines.n"}
        !           132:    which are the total number of bubble, lines, the number of bubble
        !           133:    lines for response n and number of the first bubble line for response n,
        !           134:    and a comma separated list of numbers of bubble lines for sub-questions
        !           135:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
        !           136: 
        !           137: 
        !           138: =item *
        !           139: 
        !           140: scantron_validate_missingbubbles() : 
        !           141: 
        !           142:    Validates all scanlines in the selected file to not have any
        !           143:     answers that don't have bubbles that have not been verified
        !           144:     to be bubble free.
        !           145: 
        !           146: =item *
        !           147: 
        !           148: scantron_process_students() : 
        !           149: 
        !           150:    Routine that does the actual grading of the bubble sheet information.
        !           151: 
        !           152:    The parsed scanline hash is added to %env 
        !           153: 
        !           154:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
        !           155:    foreach resource , with the form data of
        !           156: 
        !           157: 	'submitted'     =>'scantron' 
        !           158: 	'grade_target'  =>'grade',
        !           159: 	'grade_username'=> username of student
        !           160: 	'grade_domain'  => domain of student
        !           161: 	'grade_courseid'=> of course
        !           162: 	'grade_symb'    => symb of resource to grade
        !           163: 
        !           164:     This triggers a grading pass. The problem grading code takes care
        !           165:     of converting the bubbled letter information (now in %env) into a
        !           166:     valid submission.
        !           167: 
        !           168: =item *
        !           169: 
        !           170: scantron_upload_scantron_data() :
        !           171: 
        !           172:     Creates the screen for adding a new bubble sheet data file to a course.
        !           173: 
        !           174: =item *
        !           175: 
        !           176: scantron_upload_scantron_data_save() : 
        !           177: 
        !           178:    Adds a provided bubble information data file to the course if user
        !           179:    has the correct privileges to do so. 
        !           180: 
        !           181: =item *
        !           182: 
        !           183: valid_file() :
        !           184: 
        !           185:    Validates that the requested bubble data file exists in the course.
        !           186: 
        !           187: =item *
        !           188: 
        !           189: scantron_download_scantron_data() : 
        !           190: 
        !           191:    Shows a list of the three internal files (original, corrected,
        !           192:    skipped) for a specific bubble sheet data file that exists in the
        !           193:    course.
        !           194: 
        !           195: =item *
        !           196: 
        !           197: scantron_validate_ID() : 
        !           198: 
        !           199:    Validates all scanlines in the selected file to not have any
        !           200:    invalid or underspecified student IDs
        !           201: 
        !           202: =back
        !           203: 
        !           204: =cut
        !           205: 
1.1       albertel  206: package Apache::grades;
                    207: use strict;
                    208: use Apache::style;
                    209: use Apache::lonxml;
                    210: use Apache::lonnet;
1.3       albertel  211: use Apache::loncommon;
1.112     ng        212: use Apache::lonhtmlcommon;
1.68      ng        213: use Apache::lonnavmaps;
1.1       albertel  214: use Apache::lonhomework;
1.456     banghart  215: use Apache::lonpickcode;
1.55      matthew   216: use Apache::loncoursedata;
1.362     albertel  217: use Apache::lonmsg();
1.1       albertel  218: use Apache::Constants qw(:common);
1.167     sakharuk  219: use Apache::lonlocal;
1.386     raeburn   220: use Apache::lonenc;
1.170     albertel  221: use String::Similarity;
1.359     www       222: use LONCAPA;
                    223: 
1.315     bowersj2  224: use POSIX qw(floor);
1.87      www       225: 
1.435     foxr      226: 
1.513     foxr      227: 
1.435     foxr      228: my %perm=();
1.447     foxr      229: 
1.513     foxr      230: #  These variables are used to recover from ssi errors
                    231: 
                    232: my $ssi_retries = 5;
                    233: my $ssi_error;
                    234: my $ssi_error_resource;
                    235: my $ssi_error_message;
                    236: 
                    237: 
                    238: sub ssi_with_retries {
                    239:     my ($resource, $retries, %form) = @_;
                    240:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                    241:     if ($response->is_error) {
                    242: 	$ssi_error          = 1;
                    243: 	$ssi_error_resource = $resource;
                    244: 	$ssi_error_message  = $response->code . " " . $response->message;
                    245:     }
                    246: 
                    247:     return $content;
                    248: 
                    249: }
                    250: #
                    251: #  Prodcuces an ssi retry failure error message to the user:
                    252: #
                    253: 
                    254: sub ssi_print_error {
                    255:     my ($r) = @_;
1.516     raeburn   256:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                    257:     $r->print('
                    258: <br />
                    259: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                    260: <p>
                    261: '.&mt('Unable to retrieve a resource from a server:').'<br />
                    262: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                    263: '.&mt('Error:').' '.$ssi_error_message.'
                    264: </p>
                    265: <p>'.
                    266: &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 />'.
                    267: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                    268: '</p>');
                    269:     return;
1.513     foxr      270: }
                    271: 
1.44      ng        272: #
1.146     albertel  273: # --- Retrieve the parts from the metadata file.---
1.44      ng        274: sub getpartlist {
1.324     albertel  275:     my ($symb) = @_;
1.439     albertel  276: 
                    277:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    278:     my $res      = $navmap->getBySymb($symb);
                    279:     my $partlist = $res->parts();
                    280:     my $url      = $res->src();
                    281:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    282: 
1.146     albertel  283:     my @stores;
1.439     albertel  284:     foreach my $part (@{ $partlist }) {
1.146     albertel  285: 	foreach my $key (@metakeys) {
                    286: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    287: 	}
                    288:     }
                    289:     return @stores;
1.2       albertel  290: }
                    291: 
1.44      ng        292: # --- Get the symbolic name of a problem and the url
1.324     albertel  293: sub get_symb {
1.173     albertel  294:     my ($request,$silent) = @_;
1.257     albertel  295:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    296:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  297:     if ($symb eq '') { 
                    298: 	if (!$silent) {
                    299: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    300: 	    return ();
                    301: 	}
                    302:     }
1.418     albertel  303:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  304:     return ($symb);
1.32      ng        305: }
                    306: 
1.129     ng        307: #--- Format fullname, username:domain if different for display
                    308: #--- Use anywhere where the student names are listed
                    309: sub nameUserString {
                    310:     my ($type,$fullname,$uname,$udom) = @_;
                    311:     if ($type eq 'header') {
1.485     albertel  312: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        313:     } else {
1.398     albertel  314: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    315: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        316:     }
                    317: }
                    318: 
1.44      ng        319: #--- Get the partlist and the response type for a given problem. ---
                    320: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        321: sub response_type {
1.324     albertel  322:     my ($symb) = shift;
1.377     albertel  323: 
                    324:     my $navmap = Apache::lonnavmaps::navmap->new();
                    325:     my $res = $navmap->getBySymb($symb);
                    326:     my $partlist = $res->parts();
1.392     albertel  327:     my %vPart = 
                    328: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  329:     my (%response_types,%handgrade);
                    330:     foreach my $part (@{ $partlist }) {
1.392     albertel  331: 	next if (%vPart && !exists($vPart{$part}));
                    332: 
1.377     albertel  333: 	my @types = $res->responseType($part);
                    334: 	my @ids = $res->responseIds($part);
                    335: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    336: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    337: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    338: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    339: 				     '.handgrade',$symb);
1.41      ng        340: 	}
                    341:     }
1.377     albertel  342:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        343: }
                    344: 
1.375     albertel  345: sub flatten_responseType {
                    346:     my ($responseType) = @_;
                    347:     my @part_response_id =
                    348: 	map { 
                    349: 	    my $part = $_;
                    350: 	    map {
                    351: 		[$part,$_]
                    352: 		} sort(keys(%{ $responseType->{$part} }));
                    353: 	} sort(keys(%$responseType));
                    354:     return @part_response_id;
                    355: }
                    356: 
1.207     albertel  357: sub get_display_part {
1.324     albertel  358:     my ($partID,$symb)=@_;
1.207     albertel  359:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    360:     if (defined($display) and $display ne '') {
1.398     albertel  361: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  362:     } else {
                    363: 	$display=$partID;
                    364:     }
                    365:     return $display;
                    366: }
1.269     raeburn   367: 
1.118     ng        368: #--- Show resource title
                    369: #--- and parts and response type
                    370: sub showResourceInfo {
1.324     albertel  371:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  372:     my $col=3;
                    373:     if ($checkboxes) { $col=4; }
1.398     albertel  374:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    375:     $result .='<table border="0">';
1.324     albertel  376:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        377:     my %resptype = ();
1.122     ng        378:     my $hdgrade='no';
1.154     albertel  379:     my %partsseen;
1.524     raeburn   380:     foreach my $partID (sort(keys(%$responseType))) {
                    381: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
1.375     albertel  382: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    383: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    384: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    385: 	    $result.='<tr>';
                    386: 	    if ($checkboxes) {
                    387: 		if (exists($partsseen{$partID})) {
                    388: 		    $result.="<td>&nbsp;</td>";
                    389: 		} else {
1.401     albertel  390: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  391: 		}
                    392: 		$partsseen{$partID}=1;
1.154     albertel  393: 	    }
1.375     albertel  394: 	    my $display_part=&get_display_part($partID,$symb);
1.485     albertel  395: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
1.398     albertel  396: 		$resID.'</span></td>'.
1.485     albertel  397: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
                    398: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
1.154     albertel  399: 	}
1.118     ng        400:     }
                    401:     $result.='</table>'."\n";
1.147     albertel  402:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        403: }
                    404: 
1.434     albertel  405: sub reset_caches {
                    406:     &reset_analyze_cache();
                    407:     &reset_perm();
                    408: }
                    409: 
                    410: {
                    411:     my %analyze_cache;
1.148     albertel  412: 
1.434     albertel  413:     sub reset_analyze_cache {
                    414: 	undef(%analyze_cache);
                    415:     }
                    416: 
                    417:     sub get_analyze {
1.525     raeburn   418: 	my ($symb,$uname,$udom,$no_increment)=@_;
1.434     albertel  419: 	my $key = "$symb\0$uname\0$udom";
                    420: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    421: 
                    422: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    423: 	$url=&Apache::lonnet::clutter($url);
1.513     foxr      424: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
1.516     raeburn   425: 					   ('grade_target' => 'analyze',
                    426: 					    'grade_domain' => $udom,
                    427: 					    'grade_symb' => $symb,
                    428: 					    'grade_courseid' => 
                    429: 					    $env{'request.course.id'},
1.525     raeburn   430: 					    'grade_username' => $uname,
                    431:                                             'grade_noincrement' => $no_increment));
1.434     albertel  432: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    433: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    434: 	return $analyze_cache{$key} = \%analyze;
                    435:     }
                    436: 
                    437:     sub get_order {
1.525     raeburn   438: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    439: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  440: 	return $analyze->{"$partid.$respid.shown"};
                    441:     }
                    442: 
                    443:     sub get_radiobutton_correct_foil {
                    444: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    445: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    446: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    447: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    448: 		return $foil;
                    449: 	    }
                    450: 	}
                    451:     }
1.148     albertel  452: }
1.434     albertel  453: 
1.118     ng        454: #--- Clean response type for display
1.335     albertel  455: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    456: #        response types only.
1.118     ng        457: sub cleanRecord {
1.336     albertel  458:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    459: 	$uname,$udom) = @_;
1.398     albertel  460:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  461:     if ($response =~ /^(option|rank)$/) {
                    462: 	my %answer=&Apache::lonnet::str2hash($answer);
                    463: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    464: 	my ($toprow,$bottomrow);
                    465: 	foreach my $foil (@$order) {
                    466: 	    if ($grading{$foil} == 1) {
                    467: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    468: 	    } else {
                    469: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    470: 	    }
1.398     albertel  471: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  472: 	}
                    473: 	return '<blockquote><table border="1">'.
1.466     albertel  474: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    475: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  476: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    477:     } elsif ($response eq 'match') {
                    478: 	my %answer=&Apache::lonnet::str2hash($answer);
                    479: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    480: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    481: 	my ($toprow,$middlerow,$bottomrow);
                    482: 	foreach my $foil (@$order) {
                    483: 	    my $item=shift(@items);
                    484: 	    if ($grading{$foil} == 1) {
                    485: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  486: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  487: 	    } else {
                    488: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  489: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  490: 	    }
1.398     albertel  491: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        492: 	}
1.126     ng        493: 	return '<blockquote><table border="1">'.
1.466     albertel  494: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    495: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  496: 	    $middlerow.'</tr>'.
1.466     albertel  497: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  498: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    499:     } elsif ($response eq 'radiobutton') {
                    500: 	my %answer=&Apache::lonnet::str2hash($answer);
                    501: 	my ($toprow,$bottomrow);
1.434     albertel  502: 	my $correct = 
                    503: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    504: 	foreach my $foil (@$order) {
1.148     albertel  505: 	    if (exists($answer{$foil})) {
1.434     albertel  506: 		if ($foil eq $correct) {
1.466     albertel  507: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  508: 		} else {
1.466     albertel  509: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  510: 		}
                    511: 	    } else {
1.466     albertel  512: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  513: 	    }
1.398     albertel  514: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  515: 	}
                    516: 	return '<blockquote><table border="1">'.
1.466     albertel  517: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    518: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  519: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    520:     } elsif ($response eq 'essay') {
1.257     albertel  521: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        522: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  523: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    524: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        525: 
1.257     albertel  526: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    527: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    528: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    529: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    530: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    531: 	    $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        532: 	}
1.166     albertel  533: 	$answer =~ s-\n-<br />-g;
                    534: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  535:     } elsif ( $response eq 'organic') {
                    536: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    537: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    538: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    539: 	return $result;
1.335     albertel  540:     } elsif ( $response eq 'Task') {
                    541: 	if ( $answer eq 'SUBMITTED') {
                    542: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  543: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  544: 	    return $result;
                    545: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    546: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    547: 			       keys(%{$record}));
                    548: 	    return join('<br />',($version,@matches));
                    549: 			       
                    550: 			       
                    551: 	} else {
                    552: 	    my $result =
                    553: 		'<p>'
                    554: 		.&mt('Overall result: [_1]',
                    555: 		     $record->{$version."resource.$respid.$partid.status"})
                    556: 		.'</p>';
                    557: 	    
                    558: 	    $result .= '<ul>';
                    559: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    560: 			     keys(%{$record}));
                    561: 	    foreach my $grade (sort(@grade)) {
                    562: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    563: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    564: 				     $dim, $record->{$grade}).
                    565: 			  '</li>';
                    566: 	    }
                    567: 	    $result.='</ul>';
                    568: 	    return $result;
                    569: 	}
1.440     albertel  570:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    571: 	$answer = 
                    572: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    573: 							      $answer);
1.122     ng        574:     }
1.118     ng        575:     return $answer;
                    576: }
                    577: 
                    578: #-- A couple of common js functions
                    579: sub commonJSfunctions {
                    580:     my $request = shift;
                    581:     $request->print(<<COMMONJSFUNCTIONS);
                    582: <script type="text/javascript" language="javascript">
                    583:     function radioSelection(radioButton) {
                    584: 	var selection=null;
                    585: 	if (radioButton.length > 1) {
                    586: 	    for (var i=0; i<radioButton.length; i++) {
                    587: 		if (radioButton[i].checked) {
                    588: 		    return radioButton[i].value;
                    589: 		}
                    590: 	    }
                    591: 	} else {
                    592: 	    if (radioButton.checked) return radioButton.value;
                    593: 	}
                    594: 	return selection;
                    595:     }
                    596: 
                    597:     function pullDownSelection(selectOne) {
                    598: 	var selection="";
                    599: 	if (selectOne.length > 1) {
                    600: 	    for (var i=0; i<selectOne.length; i++) {
                    601: 		if (selectOne[i].selected) {
                    602: 		    return selectOne[i].value;
                    603: 		}
                    604: 	    }
                    605: 	} else {
1.138     albertel  606:             // only one value it must be the selected one
                    607: 	    return selectOne.value;
1.118     ng        608: 	}
                    609:     }
                    610: </script>
                    611: COMMONJSFUNCTIONS
                    612: }
                    613: 
1.44      ng        614: #--- Dumps the class list with usernames,list of sections,
                    615: #--- section, ids and fullnames for each user.
                    616: sub getclasslist {
1.449     banghart  617:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  618:     my @getsec;
1.450     banghart  619:     my @getgroup;
1.442     banghart  620:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  621:     if (!ref($getsec)) {
                    622: 	if ($getsec ne '' && $getsec ne 'all') {
                    623: 	    @getsec=($getsec);
                    624: 	}
                    625:     } else {
                    626: 	@getsec=@{$getsec};
                    627:     }
                    628:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  629:     if (!ref($getgroup)) {
                    630: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    631: 	    @getgroup=($getgroup);
                    632: 	}
                    633:     } else {
                    634: 	@getgroup=@{$getgroup};
                    635:     }
                    636:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  637: 
1.449     banghart  638:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  639:     # Bail out if we were unable to get the classlist
1.56      matthew   640:     return if (! defined($classlist));
1.449     banghart  641:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   642:     #
                    643:     my %sections;
                    644:     my %fullnames;
1.205     matthew   645:     foreach my $student (keys(%$classlist)) {
                    646:         my $end      = 
                    647:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    648:         my $start    = 
                    649:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    650:         my $id       = 
                    651:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    652:         my $section  = 
                    653:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    654:         my $fullname = 
                    655:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    656:         my $status   = 
                    657:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  658:         my $group   = 
                    659:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        660: 	# filter students according to status selected
1.442     banghart  661: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    662: 	    if (!($stu_status =~ $status)) {
1.450     banghart  663: 		delete($classlist->{$student});
1.76      ng        664: 		next;
                    665: 	    }
                    666: 	}
1.450     banghart  667: 	# filter students according to groups selected
1.453     banghart  668: 	my @stu_groups = split(/,/,$group);
1.450     banghart  669: 	if (@getgroup) {
                    670: 	    my $exclude = 1;
1.454     banghart  671: 	    foreach my $grp (@getgroup) {
                    672: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  673: 	            if ($stu_group eq $grp) {
                    674: 	                $exclude = 0;
                    675:     	            } 
1.450     banghart  676: 	        }
1.453     banghart  677:     	        if (($grp eq 'none') && !$group) {
                    678:         	        $exclude = 0;
                    679:         	}
1.450     banghart  680: 	    }
                    681: 	    if ($exclude) {
                    682: 	        delete($classlist->{$student});
                    683: 	    }
                    684: 	}
1.205     matthew   685: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  686: 	if (&canview($section)) {
1.291     albertel  687: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  688: 		$sections{$section}++;
1.450     banghart  689: 		if ($classlist->{$student}) {
                    690: 		    $fullnames{$student}=$fullname;
                    691: 		}
1.103     albertel  692: 	    } else {
1.205     matthew   693: 		delete($classlist->{$student});
1.103     albertel  694: 	    }
                    695: 	} else {
1.205     matthew   696: 	    delete($classlist->{$student});
1.103     albertel  697: 	}
1.44      ng        698:     }
                    699:     my %seen = ();
1.56      matthew   700:     my @sections = sort(keys(%sections));
                    701:     return ($classlist,\@sections,\%fullnames);
1.44      ng        702: }
                    703: 
1.103     albertel  704: sub canmodify {
                    705:     my ($sec)=@_;
                    706:     if ($perm{'mgr'}) {
                    707: 	if (!defined($perm{'mgr_section'})) {
                    708: 	    # can modify whole class
                    709: 	    return 1;
                    710: 	} else {
                    711: 	    if ($sec eq $perm{'mgr_section'}) {
                    712: 		#can modify the requested section
                    713: 		return 1;
                    714: 	    } else {
                    715: 		# can't modify the request section
                    716: 		return 0;
                    717: 	    }
                    718: 	}
                    719:     }
                    720:     #can't modify
                    721:     return 0;
                    722: }
                    723: 
                    724: sub canview {
                    725:     my ($sec)=@_;
                    726:     if ($perm{'vgr'}) {
                    727: 	if (!defined($perm{'vgr_section'})) {
                    728: 	    # can modify whole class
                    729: 	    return 1;
                    730: 	} else {
                    731: 	    if ($sec eq $perm{'vgr_section'}) {
                    732: 		#can modify the requested section
                    733: 		return 1;
                    734: 	    } else {
                    735: 		# can't modify the request section
                    736: 		return 0;
                    737: 	    }
                    738: 	}
                    739:     }
                    740:     #can't modify
                    741:     return 0;
                    742: }
                    743: 
1.44      ng        744: #--- Retrieve the grade status of a student for all the parts
                    745: sub student_gradeStatus {
1.324     albertel  746:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  747:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        748:     my %partstatus = ();
                    749:     foreach (@$partlist) {
1.128     ng        750: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        751: 	$status              = 'nothing' if ($status eq '');
                    752: 	$partstatus{$_}      = $status;
                    753: 	my $subkey           = "resource.$_.submitted_by";
                    754: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    755:     }
                    756:     return %partstatus;
                    757: }
                    758: 
1.45      ng        759: # hidden form and javascript that calls the form
                    760: # Use by verifyscript and viewgrades
                    761: # Shows a student's view of problem and submission
                    762: sub jscriptNform {
1.324     albertel  763:     my ($symb) = @_;
1.442     banghart  764:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        765:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    766: 	'    function viewOneStudent(user,domain) {'."\n".
                    767: 	'	document.onestudent.student.value = user;'."\n".
                    768: 	'	document.onestudent.userdom.value = domain;'."\n".
                    769: 	'	document.onestudent.submit();'."\n".
                    770: 	'    }'."\n".
                    771: 	'</script>'."\n";
                    772:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  773: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  774: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    775: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  776: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        777: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    778: 	'<input type="hidden" name="student" value="" />'."\n".
                    779: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    780: 	'</form>'."\n";
                    781:     return $jscript;
                    782: }
1.39      ng        783: 
1.447     foxr      784: 
                    785: 
1.315     bowersj2  786: # Given the score (as a number [0-1] and the weight) what is the final
                    787: # point value? This function will round to the nearest tenth, third,
                    788: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  789: sub compute_points {
1.315     bowersj2  790:     my ($score, $weight) = @_;
                    791:     
                    792:     my $tolerance = .00001;
                    793:     my $points = $score * $weight;
                    794: 
                    795:     # Check for nearness to 1/x.
                    796:     my $check_for_nearness = sub {
                    797:         my ($factor) = @_;
                    798:         my $num = ($points * $factor) + $tolerance;
                    799:         my $floored_num = floor($num);
1.316     albertel  800:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  801:             return $floored_num / $factor;
                    802:         }
                    803:         return $points;
                    804:     };
                    805: 
                    806:     $points = $check_for_nearness->(10);
                    807:     $points = $check_for_nearness->(3);
                    808:     $points = $check_for_nearness->(4);
                    809:     
                    810:     return $points;
                    811: }
                    812: 
1.44      ng        813: #------------------ End of general use routines --------------------
1.87      www       814: 
                    815: #
                    816: # Find most similar essay
                    817: #
                    818: 
                    819: sub most_similar {
1.426     albertel  820:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       821: 
                    822: # ignore spaces and punctuation
                    823: 
                    824:     $uessay=~s/\W+/ /gs;
                    825: 
1.282     www       826: # ignore empty submissions (occuring when only files are sent)
                    827: 
                    828:     unless ($uessay=~/\w+/) { return ''; }
                    829: 
1.87      www       830: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       831:     my $limit=0.6;
1.87      www       832:     my $sname='';
                    833:     my $sdom='';
                    834:     my $scrsid='';
                    835:     my $sessay='';
                    836: # go through all essays ...
1.426     albertel  837:     foreach my $tkey (keys(%$old_essays)) {
                    838: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       839: # ... except the same student
1.426     albertel  840:         next if (($tname eq $uname) && ($tdom eq $udom));
                    841: 	my $tessay=$old_essays->{$tkey};
                    842: 	$tessay=~s/\W+/ /gs;
1.87      www       843: # String similarity gives up if not even limit
1.426     albertel  844: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       845: # Found one
1.426     albertel  846: 	if ($tsimilar>$limit) {
                    847: 	    $limit=$tsimilar;
                    848: 	    $sname=$tname;
                    849: 	    $sdom=$tdom;
                    850: 	    $scrsid=$tcrsid;
                    851: 	    $sessay=$old_essays->{$tkey};
                    852: 	}
1.87      www       853:     }
1.88      www       854:     if ($limit>0.6) {
1.87      www       855:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    856:     } else {
                    857:        return ('','','','',0);
                    858:     }
                    859: }
                    860: 
1.44      ng        861: #-------------------------------------------------------------------
                    862: 
                    863: #------------------------------------ Receipt Verification Routines
1.45      ng        864: #
1.44      ng        865: #--- Check whether a receipt number is valid.---
                    866: sub verifyreceipt {
                    867:     my $request  = shift;
                    868: 
1.257     albertel  869:     my $courseid = $env{'request.course.id'};
1.184     www       870:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  871: 	$env{'form.receipt'};
1.44      ng        872:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  873:     my ($symb)   = &get_symb($request);
1.44      ng        874: 
1.487     albertel  875:     my $title.=
                    876: 	'<h3><span class="LC_info">'.
                    877: 	&mt('Verifying Submission Receipt [_1]',$receipt).
                    878: 	'</span></h3>'."\n".
                    879: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    880: 	'</h4>'."\n";
1.44      ng        881: 
                    882:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   883:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  884:     
                    885:     my $receiptparts=0;
1.390     albertel  886:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    887: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  888:     my $parts=['0'];
1.324     albertel  889:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.486     albertel  890:     
                    891:     my $header = 
                    892: 	&Apache::loncommon::start_data_table().
                    893: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  894: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    895: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    896: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  897:     if ($receiptparts) {
1.487     albertel  898: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  899:     }
                    900:     $header.=
                    901: 	&Apache::loncommon::end_data_table_header_row();
                    902: 
1.294     albertel  903:     foreach (sort 
                    904: 	     {
                    905: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    906: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    907: 		 }
                    908: 		 return $a cmp $b;
                    909: 	     } (keys(%$fullname))) {
1.44      ng        910: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  911: 	foreach my $part (@$parts) {
                    912: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  913: 		$contents.=
                    914: 		    &Apache::loncommon::start_data_table_row().
                    915: 		    '<td>&nbsp;'."\n".
1.177     albertel  916: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  917: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  918: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    919: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    920: 		if ($receiptparts) {
                    921: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    922: 		}
1.486     albertel  923: 		$contents.= 
                    924: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  925: 		
                    926: 		$matches++;
                    927: 	    }
1.44      ng        928: 	}
                    929:     }
                    930:     if ($matches == 0) {
1.487     albertel  931: 	$string = $title.&mt('No match found for the above receipt.');
1.44      ng        932:     } else {
1.324     albertel  933: 	$string = &jscriptNform($symb).$title.
1.487     albertel  934: 	    '<p>'.
                    935: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
                    936: 	    '</p>'.
1.486     albertel  937: 	    $header.
                    938: 	    $contents.
                    939: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        940:     }
1.324     albertel  941:     return $string.&show_grading_menu_form($symb);
1.44      ng        942: }
                    943: 
                    944: #--- This is called by a number of programs.
                    945: #--- Called from the Grading Menu - View/Grade an individual student
                    946: #--- Also called directly when one clicks on the subm button 
                    947: #    on the problem page.
1.30      ng        948: sub listStudents {
1.41      ng        949:     my ($request) = shift;
1.49      albertel  950: 
1.324     albertel  951:     my ($symb) = &get_symb($request);
1.257     albertel  952:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    953:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    954:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  955:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  956:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    957:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    958:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    959: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  960: 
1.485     albertel  961:     my $result='<h3><span class="LC_info">&nbsp;'.
                    962: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
                    963: 	.'</span></h3>';
1.118     ng        964: 
1.324     albertel  965:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  966: 
1.485     albertel  967:     my %lt = ( 'multiple' =>
                    968: 	       "Please select a student or group of students before clicking on the Next button.",
                    969: 	       'single'   =>
                    970: 	       "Please select the student before clicking on the Next button.",
                    971: 	       );
                    972:     %lt = &Apache::lonlocal::texthash(%lt);
1.45      ng        973:     $request->print(<<LISTJAVASCRIPT);
                    974: <script type="text/javascript" language="javascript">
1.110     ng        975:     function checkSelect(checkBox) {
                    976: 	var ctr=0;
                    977: 	var sense="";
                    978: 	if (checkBox.length > 1) {
                    979: 	    for (var i=0; i<checkBox.length; i++) {
                    980: 		if (checkBox[i].checked) {
                    981: 		    ctr++;
                    982: 		}
                    983: 	    }
1.485     albertel  984: 	    sense = '$lt{'multiple'}';
1.110     ng        985: 	} else {
                    986: 	    if (checkBox.checked) {
                    987: 		ctr = 1;
                    988: 	    }
1.485     albertel  989: 	    sense = '$lt{'single'}';
1.110     ng        990: 	}
                    991: 	if (ctr == 0) {
1.485     albertel  992: 	    alert(sense);
1.110     ng        993: 	    return false;
                    994: 	}
                    995: 	document.gradesub.submit();
                    996:     }
                    997: 
                    998:     function reLoadList(formname) {
1.112     ng        999: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng       1000: 	formname.command.value = 'submission';
                   1001: 	formname.submit();
                   1002:     }
1.45      ng       1003: </script>
                   1004: LISTJAVASCRIPT
                   1005: 
1.118     ng       1006:     &commonJSfunctions($request);
1.41      ng       1007:     $request->print($result);
1.39      ng       1008: 
1.401     albertel 1009:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                   1010:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel 1011:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel 1012: 	"\n".$table;
                   1013: 	
                   1014:     $gradeTable .= 
                   1015: 	'&nbsp;'.
                   1016: 	&mt('<b>View Problem Text: </b>[_1]',
                   1017: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   1018: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
                   1019: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
                   1020:     $gradeTable .= 
                   1021: 	'&nbsp;'.
                   1022: 	&mt('<b>View Answer: </b>[_1]',
                   1023: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
                   1024: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
                   1025: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
                   1026: 
                   1027:     my $submission_options;
1.257     albertel 1028:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel 1029: 	$submission_options.=
                   1030: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel 1031:     }
1.442     banghart 1032:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1033:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1034:     $env{'form.Status'} = $saveStatus;
1.485     albertel 1035:     $submission_options.=
                   1036: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                   1037: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                   1038: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                   1039: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
                   1040:     $gradeTable .= 
                   1041: 	'&nbsp;'.
                   1042: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
                   1043: 
                   1044:     $gradeTable .= 
                   1045:         '&nbsp;'.
                   1046: 	&mt('<b>Grading Increments:</b> [_1]',
                   1047: 	    '<select name="increment">'.
                   1048: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
                   1049: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
                   1050: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
                   1051: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
                   1052: 	    '</select>');
                   1053:     
                   1054:     $gradeTable .= 
1.432     banghart 1055:         &build_section_inputs().
1.45      ng       1056: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel 1057: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                   1058: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                   1059: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                   1060: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel 1061: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1062: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1063: 
1.257     albertel 1064:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart 1065: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng       1066:     } else {
1.485     albertel 1067: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
                   1068: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
1.124     ng       1069:     }
1.112     ng       1070: 
1.485     albertel 1071:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                   1072: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
1.110     ng       1073: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel 1074: 
                   1075: # checkall buttons
                   1076:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1077:     $gradeTable.='<input type="button" '."\n".
1.45      ng       1078: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.485     albertel 1079: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
1.249     albertel 1080:     $gradeTable.=&check_buttons();
1.485     albertel 1081:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
1.450     banghart 1082:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1083:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1084: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1085:     my $loop = 0;
                   1086:     while ($loop < 2) {
1.485     albertel 1087: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1088: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1089: 	if ($env{'form.showgrading'} eq 'yes' 
                   1090: 	    && $submitonly ne 'queued'
                   1091: 	    && $submitonly ne 'all') {
1.485     albertel 1092: 	    foreach my $part (sort(@$partlist)) {
                   1093: 		my $display_part=
                   1094: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1095: 		$gradeTable.=
                   1096: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1097: 	    }
1.301     albertel 1098: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1099: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1100: 	}
                   1101: 	$loop++;
1.126     ng       1102: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1103:     }
1.474     albertel 1104:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1105: 
1.45      ng       1106:     my $ctr = 0;
1.294     albertel 1107:     foreach my $student (sort 
                   1108: 			 {
                   1109: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1110: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1111: 			     }
                   1112: 			     return $a cmp $b;
                   1113: 			 }
                   1114: 			 (keys(%$fullname))) {
1.41      ng       1115: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1116: 
1.110     ng       1117: 	my %status = ();
1.301     albertel 1118: 
                   1119: 	if ($submitonly eq 'queued') {
                   1120: 	    my %queue_status = 
                   1121: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1122: 							$udom,$uname);
                   1123: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1124: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1125: 	}
                   1126: 
                   1127: 	if ($env{'form.showgrading'} eq 'yes' 
                   1128: 	    && $submitonly ne 'queued'
                   1129: 	    && $submitonly ne 'all') {
1.324     albertel 1130: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1131: 	    my $submitted = 0;
1.164     albertel 1132: 	    my $graded = 0;
1.248     albertel 1133: 	    my $incorrect = 0;
1.110     ng       1134: 	    foreach (keys(%status)) {
1.145     albertel 1135: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1136: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1137: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1138: 		
1.110     ng       1139: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1140: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1141: 		    $submitted = 0;
1.150     albertel 1142: 		    my ($part)=split(/\./,$partid);
1.110     ng       1143: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1144: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1145: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1146: 		}
1.41      ng       1147: 	    }
1.248     albertel 1148: 	    
1.156     albertel 1149: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1150: 				     $submitonly eq 'incorrect' ||
                   1151: 				     $submitonly eq 'graded'));
1.248     albertel 1152: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1153: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1154: 	}
1.34      ng       1155: 
1.45      ng       1156: 	$ctr++;
1.249     albertel 1157: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1158:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1159: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1160: 	    if ($ctr%2 ==1) {
                   1161: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1162: 	    }
1.126     ng       1163: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel 1164:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                   1165:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1166: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1167: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1168: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1169: 
1.257     albertel 1170: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1171: 		foreach (sort(keys(%status))) {
1.485     albertel 1172: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1173: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1174: 		}
1.41      ng       1175: 	    }
1.126     ng       1176: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1177: 	    if ($ctr%2 ==0) {
                   1178: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1179: 	    }
1.41      ng       1180: 	}
                   1181:     }
1.110     ng       1182:     if ($ctr%2 ==1) {
1.126     ng       1183: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1184: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1185: 		&& $submitonly ne 'queued'
                   1186: 		&& $submitonly ne 'all') {
1.110     ng       1187: 		foreach (@$partlist) {
                   1188: 		    $gradeTable.='<td>&nbsp;</td>';
                   1189: 		}
1.301     albertel 1190: 	    } elsif ($submitonly eq 'queued') {
                   1191: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1192: 	    }
1.474     albertel 1193: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1194:     }
                   1195: 
1.474     albertel 1196:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1197: 	'<input type="button" '.
                   1198: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.485     albertel 1199: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.45      ng       1200:     if ($ctr == 0) {
1.96      albertel 1201: 	my $num_students=(scalar(keys(%$fullname)));
                   1202: 	if ($num_students eq 0) {
1.485     albertel 1203: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1204: 	} else {
1.171     albertel 1205: 	    my $submissions='submissions';
                   1206: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1207: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1208: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1209: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1210: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1211: 		    $num_students).
                   1212: 		'</span><br />';
1.96      albertel 1213: 	}
1.46      ng       1214:     } elsif ($ctr == 1) {
1.474     albertel 1215: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1216:     }
1.324     albertel 1217:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1218:     $request->print($gradeTable);
1.44      ng       1219:     return '';
1.10      ng       1220: }
                   1221: 
1.44      ng       1222: #---- Called from the listStudents routine
1.249     albertel 1223: 
                   1224: sub check_script {
                   1225:     my ($form, $type)=@_;
                   1226:     my $chkallscript='<script type="text/javascript">
                   1227:     function checkall() {
                   1228:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1229:             ele = document.forms.'.$form.'.elements[i];
                   1230:             if (ele.name == "'.$type.'") {
                   1231:             document.forms.'.$form.'.elements[i].checked=true;
                   1232:                                        }
                   1233:         }
                   1234:     }
                   1235: 
                   1236:     function checksec() {
                   1237:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1238:             ele = document.forms.'.$form.'.elements[i];
                   1239:            string = document.forms.'.$form.'.chksec.value;
                   1240:            if
                   1241:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1242:               document.forms.'.$form.'.elements[i].checked=true;
                   1243:             }
                   1244:         }
                   1245:     }
                   1246: 
                   1247: 
                   1248:     function uncheckall() {
                   1249:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1250:             ele = document.forms.'.$form.'.elements[i];
                   1251:             if (ele.name == "'.$type.'") {
                   1252:             document.forms.'.$form.'.elements[i].checked=false;
                   1253:                                        }
                   1254:         }
                   1255:     }
                   1256: 
                   1257: </script>'."\n";
                   1258:     return $chkallscript;
                   1259: }
                   1260: 
                   1261: sub check_buttons {
1.485     albertel 1262:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1263:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1264:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1265:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1266:     return $buttons;
                   1267: }
                   1268: 
1.44      ng       1269: #     Displays the submissions for one student or a group of students
1.34      ng       1270: sub processGroup {
1.41      ng       1271:     my ($request)  = shift;
                   1272:     my $ctr        = 0;
1.155     albertel 1273:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1274:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1275: 
1.396     banghart 1276:     foreach my $student (@stuchecked) {
                   1277: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1278: 	$env{'form.student'}        = $uname;
                   1279: 	$env{'form.userdom'}        = $udom;
                   1280: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1281: 	&submission($request,$ctr,$total);
                   1282: 	$ctr++;
                   1283:     }
                   1284:     return '';
1.35      ng       1285: }
1.34      ng       1286: 
1.44      ng       1287: #------------------------------------------------------------------------------------
                   1288: #
                   1289: #-------------------------- Next few routines handles grading by student, essentially
                   1290: #                           handles essay response type problem/part
                   1291: #
                   1292: #--- Javascript to handle the submission page functionality ---
                   1293: sub sub_page_js {
                   1294:     my $request = shift;
                   1295:     $request->print(<<SUBJAVASCRIPT);
                   1296: <script type="text/javascript" language="javascript">
1.71      ng       1297:     function updateRadio(formname,id,weight) {
1.125     ng       1298: 	var gradeBox = formname["GD_BOX"+id];
                   1299: 	var radioButton = formname["RADVAL"+id];
                   1300: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1301: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1302: 	gradeBox.value = pts;
                   1303: 	var resetbox = false;
                   1304: 	if (isNaN(pts) || pts < 0) {
                   1305: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1306: 	    for (var i=0; i<radioButton.length; i++) {
                   1307: 		if (radioButton[i].checked) {
                   1308: 		    gradeBox.value = i;
                   1309: 		    resetbox = true;
                   1310: 		}
                   1311: 	    }
                   1312: 	    if (!resetbox) {
                   1313: 		formtextbox.value = "";
                   1314: 	    }
                   1315: 	    return;
1.44      ng       1316: 	}
1.71      ng       1317: 
                   1318: 	if (pts > weight) {
                   1319: 	    var resp = confirm("You entered a value ("+pts+
                   1320: 			       ") greater than the weight for the part. Accept?");
                   1321: 	    if (resp == false) {
1.125     ng       1322: 		gradeBox.value = oldpts;
1.71      ng       1323: 		return;
                   1324: 	    }
1.44      ng       1325: 	}
1.13      albertel 1326: 
1.71      ng       1327: 	for (var i=0; i<radioButton.length; i++) {
                   1328: 	    radioButton[i].checked=false;
                   1329: 	    if (pts == i && pts != "") {
                   1330: 		radioButton[i].checked=true;
                   1331: 	    }
                   1332: 	}
                   1333: 	updateSelect(formname,id);
1.125     ng       1334: 	formname["stores"+id].value = "0";
1.41      ng       1335:     }
1.5       albertel 1336: 
1.72      ng       1337:     function writeBox(formname,id,pts) {
1.125     ng       1338: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1339: 	if (checkSolved(formname,id) == 'update') {
                   1340: 	    gradeBox.value = pts;
                   1341: 	} else {
1.125     ng       1342: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1343: 	    gradeBox.value = oldpts;
1.125     ng       1344: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1345: 	    for (var i=0; i<radioButton.length; i++) {
                   1346: 		radioButton[i].checked=false;
1.72      ng       1347: 		if (i == oldpts) {
1.71      ng       1348: 		    radioButton[i].checked=true;
                   1349: 		}
                   1350: 	    }
1.41      ng       1351: 	}
1.125     ng       1352: 	formname["stores"+id].value = "0";
1.71      ng       1353: 	updateSelect(formname,id);
                   1354: 	return;
1.41      ng       1355:     }
1.44      ng       1356: 
1.71      ng       1357:     function clearRadBox(formname,id) {
                   1358: 	if (checkSolved(formname,id) == 'noupdate') {
                   1359: 	    updateSelect(formname,id);
                   1360: 	    return;
                   1361: 	}
1.125     ng       1362: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1363: 	for (var i=0; i<gradeSelect.length; i++) {
                   1364: 	    if (gradeSelect[i].selected) {
                   1365: 		var selectx=i;
                   1366: 	    }
                   1367: 	}
1.125     ng       1368: 	var stores = formname["stores"+id];
1.71      ng       1369: 	if (selectx == stores.value) { return };
1.125     ng       1370: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1371: 	gradeBox.value = "";
1.125     ng       1372: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1373: 	for (var i=0; i<radioButton.length; i++) {
                   1374: 	    radioButton[i].checked=false;
                   1375: 	}
                   1376: 	stores.value = selectx;
                   1377:     }
1.5       albertel 1378: 
1.71      ng       1379:     function checkSolved(formname,id) {
1.125     ng       1380: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1381: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1382: 	    if (!reply) {return "noupdate";}
1.120     ng       1383: 	    formname.overRideScore.value = 'yes';
1.41      ng       1384: 	}
1.71      ng       1385: 	return "update";
1.13      albertel 1386:     }
1.71      ng       1387: 
                   1388:     function updateSelect(formname,id) {
1.125     ng       1389: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1390: 	return;
1.41      ng       1391:     }
1.33      ng       1392: 
1.121     ng       1393: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1394:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1395: 	formname.gradeOpt.value = val;
1.71      ng       1396: 	if (val == "Save & Next") {
                   1397: 	    for (i=0;i<=total;i++) {
                   1398: 		for (j=0;j<parttot;j++) {
1.125     ng       1399: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1400: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1401: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1402: 			if (points == "") {
1.125     ng       1403: 			    var name = formname["name"+i].value;
1.129     ng       1404: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1405: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1406: 					       ", part "+partid+". Continue?");
1.71      ng       1407: 			    if (resp == false) {
1.125     ng       1408: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1409: 				return false;
                   1410: 			    }
                   1411: 			}
                   1412: 		    }
                   1413: 		    
                   1414: 		}
                   1415: 	    }
                   1416: 	    
                   1417: 	}
1.121     ng       1418: 	if (val == "Grade Student") {
                   1419: 	    formname.showgrading.value = "yes";
                   1420: 	    if (formname.Status.value == "") {
                   1421: 		formname.Status.value = "Active";
                   1422: 	    }
                   1423: 	    formname.studentNo.value = total;
                   1424: 	}
1.120     ng       1425: 	formname.submit();
                   1426:     }
                   1427: 
1.71      ng       1428: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1429:     function checkSubmitPage(formname,total) {
                   1430: 	noscore = new Array(100);
                   1431: 	var ptr = 0;
                   1432: 	for (i=1;i<total;i++) {
1.125     ng       1433: 	    var partid = formname["q_"+i].value;
1.127     ng       1434: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1435: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1436: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1437: 		if (points == "" && status != "correct_by_student") {
                   1438: 		    noscore[ptr] = i;
                   1439: 		    ptr++;
                   1440: 		}
                   1441: 	    }
                   1442: 	}
                   1443: 	if (ptr != 0) {
                   1444: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1445: 	    var prolist = "";
                   1446: 	    if (ptr == 1) {
                   1447: 		prolist = noscore[0];
                   1448: 	    } else {
                   1449: 		var i = 0;
                   1450: 		while (i < ptr-1) {
                   1451: 		    prolist += noscore[i]+", ";
                   1452: 		    i++;
                   1453: 		}
                   1454: 		prolist += "and "+noscore[i];
                   1455: 	    }
                   1456: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1457: 	    if (resp == false) {
                   1458: 		return false;
                   1459: 	    }
                   1460: 	}
1.45      ng       1461: 
1.71      ng       1462: 	formname.submit();
                   1463:     }
                   1464: </script>
                   1465: SUBJAVASCRIPT
                   1466: }
1.45      ng       1467: 
1.71      ng       1468: #--- javascript for essay type problem --
                   1469: sub sub_page_kw_js {
                   1470:     my $request = shift;
1.80      ng       1471:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1472:     &commonJSfunctions($request);
1.350     albertel 1473: 
1.351     albertel 1474:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1475:     <script text="text/javascript">
                   1476:     function checkInput() {
                   1477:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1478:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1479:       var usrctr = document.msgcenter.usrctr.value;
                   1480:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1481:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1482: 
                   1483:       var msgchk = "";
                   1484:       if (document.msgcenter.subchk.checked) {
                   1485:          msgchk = "msgsub,";
                   1486:       }
                   1487:       var includemsg = 0;
                   1488:       for (var i=1; i<=nmsg; i++) {
                   1489:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1490:           var frmmsg = document.msgcenter["msg"+i];
                   1491:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1492:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1493:           showflg.value = "1";
                   1494:           var chkbox = document.msgcenter["msgn"+i];
                   1495:           if (chkbox.checked) {
                   1496:              msgchk += "savemsg"+i+",";
                   1497:              includemsg = 1;
                   1498:           }
                   1499:       }
                   1500:       if (document.msgcenter.newmsgchk.checked) {
                   1501:          msgchk += "newmsg"+usrctr;
                   1502:          includemsg = 1;
                   1503:       }
                   1504:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1505:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1506:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1507:       includemsg.value = msgchk;
                   1508: 
                   1509:       self.close()
                   1510: 
                   1511:     }
                   1512:     </script>
                   1513: INNERJS
                   1514: 
1.351     albertel 1515:     my $inner_js_highlight_central=<<INNERJS;
                   1516:  <script type="text/javascript">
                   1517:     function updateChoice(flag) {
                   1518:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1519:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1520:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1521:       opener.document.SCORE.refresh.value = "on";
                   1522:       if (opener.document.SCORE.keywords.value!=""){
                   1523:          opener.document.SCORE.submit();
                   1524:       }
                   1525:       self.close()
                   1526:     }
                   1527: </script>
                   1528: INNERJS
                   1529: 
                   1530:     my $start_page_msg_central = 
                   1531:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1532: 				       {'js_ready'  => 1,
                   1533: 					'only_body' => 1,
                   1534: 					'bgcolor'   =>'#FFFFFF',});
                   1535:     my $end_page_msg_central = 
                   1536: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1537: 
                   1538: 
                   1539:     my $start_page_highlight_central = 
                   1540:         &Apache::loncommon::start_page('Highlight Central',
                   1541: 				       $inner_js_highlight_central,
1.350     albertel 1542: 				       {'js_ready'  => 1,
                   1543: 					'only_body' => 1,
                   1544: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1545:     my $end_page_highlight_central = 
1.350     albertel 1546: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1547: 
1.219     www      1548:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1549:     $docopen=~s/^document\.//;
1.71      ng       1550:     $request->print(<<SUBJAVASCRIPT);
                   1551: <script type="text/javascript" language="javascript">
1.45      ng       1552: 
1.44      ng       1553: //===================== Show list of keywords ====================
1.122     ng       1554:   function keywords(formname) {
                   1555:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1556:     if (nret==null) return;
1.122     ng       1557:     formname.keywords.value = nret;
1.44      ng       1558: 
1.122     ng       1559:     if (formname.keywords.value != "") {
1.128     ng       1560: 	formname.refresh.value = "on";
1.122     ng       1561: 	formname.submit();
1.44      ng       1562:     }
                   1563:     return;
                   1564:   }
                   1565: 
                   1566: //===================== Script to view submitted by ==================
                   1567:   function viewSubmitter(submitter) {
                   1568:     document.SCORE.refresh.value = "on";
                   1569:     document.SCORE.NCT.value = "1";
                   1570:     document.SCORE.unamedom0.value = submitter;
                   1571:     document.SCORE.submit();
                   1572:     return;
                   1573:   }
                   1574: 
                   1575: //===================== Script to add keyword(s) ==================
                   1576:   function getSel() {
                   1577:     if (document.getSelection) txt = document.getSelection();
                   1578:     else if (document.selection) txt = document.selection.createRange().text;
                   1579:     else return;
                   1580:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1581:     if (cleantxt=="") {
1.46      ng       1582: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1583: 	return;
                   1584:     }
                   1585:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1586:     if (nret==null) return;
1.127     ng       1587:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1588:     if (document.SCORE.keywords.value != "") {
1.127     ng       1589: 	document.SCORE.refresh.value = "on";
1.44      ng       1590: 	document.SCORE.submit();
                   1591:     }
                   1592:     return;
                   1593:   }
                   1594: 
                   1595: //====================== Script for composing message ==============
1.80      ng       1596:    // preload images
                   1597:    img1 = new Image();
                   1598:    img1.src = "$iconpath/mailbkgrd.gif";
                   1599:    img2 = new Image();
                   1600:    img2.src = "$iconpath/mailto.gif";
                   1601: 
1.44      ng       1602:   function msgCenter(msgform,usrctr,fullname) {
                   1603:     var Nmsg  = msgform.savemsgN.value;
                   1604:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1605:     var subject = msgform.msgsub.value;
1.127     ng       1606:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1607:     re = /msgsub/;
                   1608:     var shwsel = "";
                   1609:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1610:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1611:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1612:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1613: 	var testmsg = "savemsg"+i+",";
                   1614: 	re = new RegExp(testmsg,"g");
1.44      ng       1615: 	shwsel = "";
                   1616: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1617: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1618: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1619: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1620: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1621:     }
1.125     ng       1622:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1623:     shwsel = "";
                   1624:     re = /newmsg/;
                   1625:     if (re.test(msgchk)) { shwsel = "checked" }
                   1626:     newMsg(newmsg,shwsel);
                   1627:     msgTail(); 
                   1628:     return;
                   1629:   }
                   1630: 
1.123     ng       1631:   function checkEntities(strx) {
                   1632:     if (strx.length == 0) return strx;
                   1633:     var orgStr = ["&", "<", ">", '"']; 
                   1634:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1635:     var counter = 0;
                   1636:     while (counter < 4) {
                   1637: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1638: 	counter++;
                   1639:     }
                   1640:     return strx;
                   1641:   }
                   1642: 
                   1643:   function strReplace(strx, orgStr, newStr) {
                   1644:     return strx.split(orgStr).join(newStr);
                   1645:   }
                   1646: 
1.44      ng       1647:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1648:     var height = 70*Nmsg+250;
1.44      ng       1649:     var scrollbar = "no";
                   1650:     if (height > 600) {
                   1651: 	height = 600;
                   1652: 	scrollbar = "yes";
                   1653:     }
1.118     ng       1654:     var xpos = (screen.width-600)/2;
                   1655:     xpos = (xpos < 0) ? '0' : xpos;
                   1656:     var ypos = (screen.height-height)/2-30;
                   1657:     ypos = (ypos < 0) ? '0' : ypos;
                   1658: 
1.206     albertel 1659:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1660:     pWin.focus();
                   1661:     pDoc = pWin.document;
1.219     www      1662:     pDoc.$docopen;
1.351     albertel 1663:     pDoc.write('$start_page_msg_central');
1.76      ng       1664: 
                   1665:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1666:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1667:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1668: 
                   1669:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1670:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1671:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1672: }
                   1673:     function displaySubject(msg,shwsel) {
1.76      ng       1674:     pDoc = pWin.document;
                   1675:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1676:     pDoc.write("<td>Subject<\\/td>");
                   1677:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1678:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1679: }
                   1680: 
1.72      ng       1681:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1682:     pDoc = pWin.document;
                   1683:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1684:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1685:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1686:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1687: }
                   1688: 
                   1689:   function newMsg(newmsg,shwsel) {
1.76      ng       1690:     pDoc = pWin.document;
                   1691:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1692:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1693:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1694:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1695: }
                   1696: 
                   1697:   function msgTail() {
1.76      ng       1698:     pDoc = pWin.document;
1.465     albertel 1699:     pDoc.write("<\\/table>");
                   1700:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1701:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1702:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1703:     pDoc.write("<\\/form>");
1.351     albertel 1704:     pDoc.write('$end_page_msg_central');
1.128     ng       1705:     pDoc.close();
1.44      ng       1706: }
                   1707: 
                   1708: //====================== Script for keyword highlight options ==============
                   1709:   function kwhighlight() {
                   1710:     var kwclr    = document.SCORE.kwclr.value;
                   1711:     var kwsize   = document.SCORE.kwsize.value;
                   1712:     var kwstyle  = document.SCORE.kwstyle.value;
                   1713:     var redsel = "";
                   1714:     var grnsel = "";
                   1715:     var blusel = "";
                   1716:     if (kwclr=="red")   {var redsel="checked"};
                   1717:     if (kwclr=="green") {var grnsel="checked"};
                   1718:     if (kwclr=="blue")  {var blusel="checked"};
                   1719:     var sznsel = "";
                   1720:     var sz1sel = "";
                   1721:     var sz2sel = "";
                   1722:     if (kwsize=="0")  {var sznsel="checked"};
                   1723:     if (kwsize=="+1") {var sz1sel="checked"};
                   1724:     if (kwsize=="+2") {var sz2sel="checked"};
                   1725:     var synsel = "";
                   1726:     var syisel = "";
                   1727:     var sybsel = "";
                   1728:     if (kwstyle=="")    {var synsel="checked"};
                   1729:     if (kwstyle=="<i>") {var syisel="checked"};
                   1730:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1731:     highlightCentral();
                   1732:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1733:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1734:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1735:     highlightend();
                   1736:     return;
                   1737:   }
                   1738: 
                   1739:   function highlightCentral() {
1.76      ng       1740: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1741:     var xpos = (screen.width-400)/2;
                   1742:     xpos = (xpos < 0) ? '0' : xpos;
                   1743:     var ypos = (screen.height-330)/2-30;
                   1744:     ypos = (ypos < 0) ? '0' : ypos;
                   1745: 
1.206     albertel 1746:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1747:     hwdWin.focus();
                   1748:     var hDoc = hwdWin.document;
1.219     www      1749:     hDoc.$docopen;
1.351     albertel 1750:     hDoc.write('$start_page_highlight_central');
1.76      ng       1751:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1752:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1753: 
                   1754:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1755:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1756:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1757:   }
                   1758: 
                   1759:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1760:     var hDoc = hwdWin.document;
                   1761:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1762:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1763:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1764:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1765:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1766:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1767:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1768:     hDoc.write("<\\/tr>");
1.44      ng       1769:   }
                   1770: 
                   1771:   function highlightend() { 
1.76      ng       1772:     var hDoc = hwdWin.document;
1.465     albertel 1773:     hDoc.write("<\\/table>");
                   1774:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1775:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1776:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1777:     hDoc.write("<\\/form>");
1.351     albertel 1778:     hDoc.write('$end_page_highlight_central');
1.128     ng       1779:     hDoc.close();
1.44      ng       1780:   }
                   1781: 
                   1782: </script>
                   1783: SUBJAVASCRIPT
                   1784: }
                   1785: 
1.349     albertel 1786: sub get_increment {
1.348     bowersj2 1787:     my $increment = $env{'form.increment'};
                   1788:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1789:         $increment != .1) {
                   1790:         $increment = 1;
                   1791:     }
                   1792:     return $increment;
                   1793: }
                   1794: 
1.71      ng       1795: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1796: sub gradeBox {
1.322     albertel 1797:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1798:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1799: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1800:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1801:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1802:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1803:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1804:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1805: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1806:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1807:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1808:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1809: 				       [$partid]);
                   1810:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1811:     if ($last_resets{$partid}) {
                   1812:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1813:     }
1.485     albertel 1814:     $result.='<table border="0"><tr>';
1.71      ng       1815:     my $ctr = 0;
1.348     bowersj2 1816:     my $thisweight = 0;
1.349     albertel 1817:     my $increment = &get_increment();
1.485     albertel 1818: 
                   1819:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1820:     while ($thisweight<=$wgt) {
1.485     albertel 1821: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1822: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1823: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1824: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1825: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1826:         $thisweight += $increment;
1.71      ng       1827: 	$ctr++;
                   1828:     }
1.485     albertel 1829:     $radio.='</tr></table>';
                   1830: 
                   1831:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1832: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1833: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1834: 	$wgt.')" /></td>'."\n";
1.485     albertel 1835:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1836: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1837: 	' </td><td>'."\n";
1.485     albertel 1838:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1839: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1840:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1841: 	$line.='<option></option>'.
                   1842: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1843:     } else {
1.485     albertel 1844: 	$line.='<option selected="selected"></option>'.
                   1845: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1846:     }
1.485     albertel 1847:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1848: 
                   1849: 
                   1850:     $result .= 
                   1851: 	&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);
                   1852: 
                   1853:     
                   1854:     $result.='</tr></table>'."\n";
1.71      ng       1855:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1856: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1857: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1858: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1859:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1860:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1861:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1862:         $aggtries.'" />'."\n";
1.323     banghart 1863:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1864:     return $result;
                   1865: }
1.322     albertel 1866: 
                   1867: sub handback_box {
1.323     banghart 1868:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1869:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1870:     my (@respids);
1.375     albertel 1871:      my @part_response_id = &flatten_responseType($responseType);
                   1872:     foreach my $part_response_id (@part_response_id) {
                   1873:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1874:         if ($part eq $partid) {
1.375     albertel 1875:             push(@respids,$resp);
1.323     banghart 1876:         }
                   1877:     }
1.318     banghart 1878:     my $result;
1.323     banghart 1879:     foreach my $respid (@respids) {
1.322     albertel 1880: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1881: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1882: 	next if (!@$files);
                   1883: 	my $file_counter = 1;
1.313     banghart 1884: 	foreach my $file (@$files) {
1.368     banghart 1885: 	    if ($file =~ /\/portfolio\//) {
                   1886:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1887:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1888:     	        $file_disp = "$name.$ext";
                   1889:     	        $file = $file_path.$file_disp;
                   1890:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1891:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1892:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1893:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1894:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1895:     	        $file_counter++;
                   1896: 	    }
1.322     albertel 1897: 	}
1.313     banghart 1898:     }
1.318     banghart 1899:     return $result;    
1.71      ng       1900: }
1.44      ng       1901: 
1.58      albertel 1902: sub show_problem {
1.382     albertel 1903:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1904:     my $rendered;
1.382     albertel 1905:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1906:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1907:     if ($mode eq 'both' or $mode eq 'text') {
                   1908: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1909: 						       $env{'request.course.id'},
                   1910: 						       undef,\%form);
1.144     albertel 1911:     }
1.58      albertel 1912:     if ($removeform) {
                   1913: 	$rendered=~s|<form(.*?)>||g;
                   1914: 	$rendered=~s|</form>||g;
1.374     albertel 1915: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1916:     }
1.144     albertel 1917:     my $companswer;
                   1918:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1919: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1920: 	$companswer=
                   1921: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1922: 						    $env{'request.course.id'},
                   1923: 						    %form);
1.144     albertel 1924:     }
1.58      albertel 1925:     if ($removeform) {
                   1926: 	$companswer=~s|<form(.*?)>||g;
                   1927: 	$companswer=~s|</form>||g;
1.144     albertel 1928: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1929:     }
1.468     albertel 1930:     $rendered=
                   1931: 	'<div class="LC_grade_show_problem_header">'.
                   1932: 	&mt('View of the problem').
                   1933: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1934: 	$rendered.
                   1935: 	'</div>';
                   1936:     $companswer=
                   1937: 	'<div class="LC_grade_show_problem_header">'.
                   1938: 	&mt('Correct answer').
                   1939: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1940: 	$companswer.
                   1941: 	'</div>';
                   1942:     my $result;
1.144     albertel 1943:     if ($mode eq 'both') {
1.468     albertel 1944: 	$result=$rendered.$companswer;
1.144     albertel 1945:     } elsif ($mode eq 'text') {
1.468     albertel 1946: 	$result=$rendered;
1.144     albertel 1947:     } elsif ($mode eq 'answer') {
1.468     albertel 1948: 	$result=$companswer;
1.144     albertel 1949:     }
1.468     albertel 1950:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1951:     return $result;
1.58      albertel 1952: }
1.397     albertel 1953: 
1.396     banghart 1954: sub files_exist {
                   1955:     my ($r, $symb) = @_;
                   1956:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1957: 
1.396     banghart 1958:     foreach my $student (@students) {
                   1959:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1960:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1961: 					      $udom,$uname);
1.396     banghart 1962:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1963:         foreach my $submission (@$string) {
                   1964:             my ($partid,$respid) =
                   1965: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1966:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1967: 					   \%record);
                   1968:             return 1 if (@$files);
1.396     banghart 1969:         }
                   1970:     }
1.397     albertel 1971:     return 0;
1.396     banghart 1972: }
1.397     albertel 1973: 
1.394     banghart 1974: sub download_all_link {
                   1975:     my ($r,$symb) = @_;
1.395     albertel 1976:     my $all_students = 
                   1977: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1978: 
                   1979:     my $parts =
                   1980: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1981: 
1.394     banghart 1982:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1983:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1984:                              'cgi.'.$identifier.'.symb' => $symb,
                   1985:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1986:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1987: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1988:     return
                   1989: }
1.395     albertel 1990: 
1.432     banghart 1991: sub build_section_inputs {
                   1992:     my $section_inputs;
                   1993:     if ($env{'form.section'} eq '') {
                   1994:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1995:     } else {
                   1996:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1997:         foreach my $section (@sections) {
1.432     banghart 1998:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1999:         }
                   2000:     }
                   2001:     return $section_inputs;
                   2002: }
                   2003: 
1.44      ng       2004: # --------------------------- show submissions of a student, option to grade 
                   2005: sub submission {
                   2006:     my ($request,$counter,$total) = @_;
1.257     albertel 2007:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2008:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2009:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2010:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 2011:     my $symb = &get_symb($request); 
                   2012:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 2013: 
                   2014:     if (!&canview($usec)) {
1.398     albertel 2015: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   2016: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   2017: 			$env{'request.course.id'}.')</span>');
1.324     albertel 2018: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 2019: 	return;
                   2020:     }
                   2021: 
1.257     albertel 2022:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2023:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2024:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2025:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2026:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2027: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2028: 	'/check.gif" height="16" border="0" />';
1.41      ng       2029: 
1.426     albertel 2030:     my %old_essays;
1.41      ng       2031:     # header info
                   2032:     if ($counter == 0) {
                   2033: 	&sub_page_js($request);
1.257     albertel 2034: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   2035: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   2036: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 2037: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 2038: 	    &download_all_link($request, $symb);
                   2039: 	}
1.485     albertel 2040: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   2041: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       2042: 
1.44      ng       2043: 	# option to display problem, only once else it cause problems 
                   2044:         # with the form later since the problem has a form.
1.257     albertel 2045: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2046: 	    my $mode;
1.257     albertel 2047: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2048: 		$mode='both';
1.257     albertel 2049: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2050: 		$mode='text';
1.257     albertel 2051: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2052: 		$mode='answer';
                   2053: 	    }
1.329     albertel 2054: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2055: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2056: 	}
1.441     www      2057: 
1.44      ng       2058: 	# kwclr is the only variable that is guaranteed to be non blank 
                   2059:         # if this subroutine has been called once.
1.41      ng       2060: 	my %keyhash = ();
1.257     albertel 2061: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2062: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2063: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2064: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2065: 
1.257     albertel 2066: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2067: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2068: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2069: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2070: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2071: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2072: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2073: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2074: 	}
1.257     albertel 2075: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2076: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2077: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2078: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2079: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2080: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2081: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2082: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2083: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2084: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2085: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2086: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2087: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2088: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2089: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2090: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2091: 			&build_section_inputs().
1.326     albertel 2092: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2093: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2094: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2095: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2096: 	if ($env{'form.handgrade'} eq 'yes') {
                   2097: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2098: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2099: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2100: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2101: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2102: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2103: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2104: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2105: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2106: 	    }
1.123     ng       2107: 	}
1.41      ng       2108: 	
                   2109: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2110: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2111: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2112: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2113: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2114: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2115: 		'" />'."\n".
                   2116: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2117: 	    $cts++;
                   2118: 	}
                   2119: 	$request->print($prnmsg);
1.32      ng       2120: 
1.257     albertel 2121: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2122: #
                   2123: # Print out the keyword options line
                   2124: #
1.41      ng       2125: 	    $request->print(<<KEYWORDS);
1.38      ng       2126: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2127: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       2128: <a href="#" onMouseDown="javascript:getSel(); return false"
                   2129:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2130: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2131: KEYWORDS
1.88      www      2132: #
                   2133: # Load the other essays for similarity check
                   2134: #
1.324     albertel 2135:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2136: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2137: 	    $apath=&escape($apath);
1.88      www      2138: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2139: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2140:         }
                   2141:     }
1.44      ng       2142: 
1.441     www      2143: # This is where output for one specific student would start
1.468     albertel 2144:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2145:     $request->print("\n\n".
1.468     albertel 2146:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2147: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2148: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2149: 
1.257     albertel 2150:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2151: 	my $mode;
1.257     albertel 2152: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2153: 	    $mode='both';
1.257     albertel 2154: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2155: 	    $mode='text';
1.257     albertel 2156: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2157: 	    $mode='answer';
                   2158: 	}
1.329     albertel 2159: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2160: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2161:     }
1.144     albertel 2162: 
1.257     albertel 2163:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2164:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2165: 
1.44      ng       2166:     # Display student info
1.41      ng       2167:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2168:     my $result='<div class="LC_grade_submissions">';
                   2169:     
                   2170:     $result.='<div class="LC_grade_submissions_header">';
                   2171:     $result.= &mt('Submissions');
1.45      ng       2172:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2173: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2174:     if ($env{'form.handgrade'} eq 'no') {
                   2175: 	$result.='<span class="LC_grade_check_note">'.
                   2176: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2177: 
                   2178:     }
                   2179: 
                   2180: 
1.41      ng       2181: 
1.118     ng       2182:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2183:     my $fullname;
                   2184:     my $col_fullnames = [];
1.257     albertel 2185:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2186: 	(my $sub_result,$fullname,$col_fullnames)=
                   2187: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2188: 				 $counter);
                   2189: 	$result.=$sub_result;
1.41      ng       2190:     }
1.44      ng       2191:     $request->print($result."\n");
1.468     albertel 2192:     $request->print('</div>'."\n");
1.44      ng       2193:     # print student answer/submission
                   2194:     # Options are (1) Handgaded submission only
                   2195:     #             (2) Last submission, includes submission that is not handgraded 
                   2196:     #                  (for multi-response type part)
                   2197:     #             (3) Last submission plus the parts info
                   2198:     #             (4) The whole record for this student
1.257     albertel 2199:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2200: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2201: 	
                   2202: 	my $lastsubonly;
                   2203: 
1.151     albertel 2204: 	if ($$timestamp eq '') {
1.468     albertel 2205: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2206: 	} else {
1.468     albertel 2207: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2208: 
1.151     albertel 2209: 	    my %seenparts;
1.375     albertel 2210: 	    my @part_response_id = &flatten_responseType($responseType);
                   2211: 	    foreach my $part (@part_response_id) {
1.393     albertel 2212: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2213: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2214: 
1.375     albertel 2215: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2216: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2217: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2218: 		    if (exists($seenparts{$partid})) { next; }
                   2219: 		    $seenparts{$partid}=1;
1.207     albertel 2220: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2221: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2222: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2223: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2224: 			'\');" target="_self">'.
1.257     albertel 2225: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2226: 		    $request->print($submitby);
                   2227: 		    next;
                   2228: 		}
                   2229: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2230: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2231: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2232: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2233: 			' )</span>&nbsp; &nbsp;'.
1.468     albertel 2234: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2235: 		    next;
                   2236: 		}
1.468     albertel 2237: 		foreach my $submission (@$string) {
                   2238: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2239: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2240: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2241: 		    # Similarity check
                   2242: 		    my $similar='';
1.257     albertel 2243: 		    if($env{'form.checkPlag'}){
1.151     albertel 2244: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2245: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2246: 			if ($osim) {
                   2247: 			    $osim=int($osim*100.0);
1.426     albertel 2248: 			    my %old_course_desc = 
                   2249: 				&Apache::lonnet::coursedescription($ocrsid,
                   2250: 								   {'one_time' => 1});
                   2251: 
                   2252: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2253: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2254: 				    $osim,
                   2255: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2256: 				    $oname,$odom,
1.426     albertel 2257: 				    $old_course_desc{'description'},
1.427     albertel 2258: 				    $old_course_desc{'num'},
1.426     albertel 2259: 				    $old_course_desc{'domain'}).
1.398     albertel 2260: 				'</span></h3><blockquote><i>'.
1.151     albertel 2261: 				&keywords_highlight($oessay).
                   2262: 				'</i></blockquote><hr />';
                   2263: 			}
1.150     albertel 2264: 		    }
1.151     albertel 2265: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2266: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2267: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2268: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2269: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2270: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2271: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2272: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2273: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2274: 			if (@$files) {
1.468     albertel 2275: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2276: 			    my $file_counter = 0;
1.313     banghart 2277: 			    foreach my $file (@$files) {
1.468     albertel 2278: 			        $file_counter++;
1.232     albertel 2279: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2280: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2281: 			    }
1.236     albertel 2282: 			    $lastsubonly.='<br />';
1.41      ng       2283: 			}
1.468     albertel 2284: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2285: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2286: 					 $respid,\%record,$order);
                   2287: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2288: 			$lastsubonly.='</div>';
1.41      ng       2289: 		    }
                   2290: 		}
                   2291: 	    }
1.468     albertel 2292: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2293: 	}
                   2294: 	$request->print($lastsubonly);
1.468     albertel 2295:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2296: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2297: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2298:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2299: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2300: 								 $env{'request.course.id'},
1.44      ng       2301: 								 $last,'.submission',
                   2302: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2303:     }
1.120     ng       2304: 
1.121     ng       2305:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2306: 	.$udom.'" />'."\n");
1.44      ng       2307:     # return if view submission with no grading option
1.257     albertel 2308:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2309: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2310: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2311: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2312: 	$toGrade.='</div>'."\n";
1.257     albertel 2313: 	if (($env{'form.command'} eq 'submission') || 
                   2314: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2315: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2316: 	}
1.180     albertel 2317: 	$request->print($toGrade);
1.41      ng       2318: 	return;
1.180     albertel 2319:     } else {
1.468     albertel 2320: 	$request->print('</div>'."\n");
1.41      ng       2321:     }
1.33      ng       2322: 
1.121     ng       2323:     # essay grading message center
1.257     albertel 2324:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2325: 	my $result='<div class="LC_grade_message_center">';
                   2326:     
                   2327: 	$result.='<div class="LC_grade_message_center_header">'.
                   2328: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2329: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2330: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2331: 	if (scalar(@$col_fullnames) > 0) {
                   2332: 	    my $lastone = pop(@$col_fullnames);
                   2333: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2334: 	}
                   2335: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2336: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2337: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2338: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2339: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2340: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2341: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2342: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2343: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2344: 	    '<br />&nbsp;('.
1.468     albertel 2345: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2346: 	$result.='</div></div>';
1.121     ng       2347: 	$request->print($result);
1.118     ng       2348:     }
1.41      ng       2349: 
                   2350:     my %seen = ();
                   2351:     my @partlist;
1.129     ng       2352:     my @gradePartRespid;
1.375     albertel 2353:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2354:     $request->print('<div class="LC_grade_assign">'.
                   2355: 		    
                   2356: 		    '<div class="LC_grade_assign_header">'.
                   2357: 		    &mt('Assign Grades').'</div>'.
                   2358: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2359:     foreach my $part_response_id (@part_response_id) {
                   2360:     	my ($partid,$respid) = @{ $part_response_id };
                   2361: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2362: 	next if ($seen{$partid} > 0);
1.41      ng       2363: 	$seen{$partid}++;
1.393     albertel 2364: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2365: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2366: 	push(@partlist,$partid);
                   2367: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2368: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2369:     }
1.468     albertel 2370:     $request->print('</div></div>');
                   2371: 
                   2372:     $request->print('<div class="LC_grade_info_links">');
                   2373:     if ($perm{'vgr'}) {
                   2374: 	$request->print(
                   2375: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2376: 						   $uname,$udom,'check'));
                   2377:     }
                   2378:     if ($perm{'opa'}) {
                   2379: 	$request->print(
                   2380: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2381: 					 $uname,$udom,$symb,'check'));
                   2382:     }
                   2383:     $request->print('</div>');
                   2384: 
1.45      ng       2385:     $result='<input type="hidden" name="partlist'.$counter.
                   2386: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2387:     $result.='<input type="hidden" name="gradePartRespid'.
                   2388: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2389:     my $ctr = 0;
                   2390:     while ($ctr < scalar(@partlist)) {
                   2391: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2392: 	    $partlist[$ctr].'" />'."\n";
                   2393: 	$ctr++;
                   2394:     }
1.468     albertel 2395:     $request->print($result.''."\n");
1.41      ng       2396: 
1.441     www      2397: # Done with printing info for one student
                   2398: 
1.468     albertel 2399:     $request->print('</div>');#LC_grade_show_user_body
                   2400:     $request->print('</div>');#LC_grade_show_user
1.441     www      2401: 
                   2402: 
1.41      ng       2403:     # print end of form
                   2404:     if ($counter == $total) {
1.297     www      2405: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2406: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2407: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2408: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2409: 	my $ntstu ='<select name="NTSTU">'.
                   2410: 	    '<option>1</option><option>2</option>'.
                   2411: 	    '<option>3</option><option>5</option>'.
                   2412: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2413: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2414: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.485     albertel 2415: 	$endform.=&mt('[_1]student(s)',$ntstu);
                   2416: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2417: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2418: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2419: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2420: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2421:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2422:             "' name='increment' />";
1.485     albertel 2423: 	$endform.='</td></tr></table></form>';
1.324     albertel 2424: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2425: 	$request->print($endform);
                   2426:     }
                   2427:     return '';
1.38      ng       2428: }
                   2429: 
1.464     albertel 2430: sub check_collaborators {
                   2431:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2432:     my ($result,@col_fullnames);
                   2433:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2434:     foreach my $part (keys(%$handgrade)) {
                   2435: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2436: 					'.maxcollaborators',
                   2437: 					$symb,$udom,$uname);
                   2438: 	next if ($ncol <= 0);
                   2439: 	$part =~ s/\_/\./g;
                   2440: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2441: 	my (@good_collaborators, @bad_collaborators);
                   2442: 	foreach my $possible_collaborator
                   2443: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2444: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2445: 	    next if ($possible_collaborator eq '');
                   2446: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2447: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2448: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2449: 	    # Doing this grep allows 'fuzzy' specification
                   2450: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2451: 			       keys(%$classlist));
                   2452: 	    if (! scalar(@matches)) {
                   2453: 		push(@bad_collaborators, $possible_collaborator);
                   2454: 	    } else {
                   2455: 		push(@good_collaborators, @matches);
                   2456: 	    }
                   2457: 	}
                   2458: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2459: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2460: 	    foreach my $name (@good_collaborators) {
                   2461: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2462: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2463: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2464: 	    }
                   2465: 	    $result.='<br />'."\n";
1.466     albertel 2466: 	    my ($part)=split(/\./,$part);
1.464     albertel 2467: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2468: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2469: 		"\n";
                   2470: 	}
                   2471: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2472: 	    $result.='<div class="LC_warning">';
1.464     albertel 2473: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2474: 	    $result .= '</div>';
                   2475: 	}         
                   2476: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2477: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2478: 	    $result .= &mt('This student has submitted too many '.
                   2479: 		'collaborators.  Maximum is [_1].',$ncol);
                   2480: 	    $result .= '</div>';
                   2481: 	}
                   2482:     }
                   2483:     return ($result,$fullname,\@col_fullnames);
                   2484: }
                   2485: 
1.44      ng       2486: #--- Retrieve the last submission for all the parts
1.38      ng       2487: sub get_last_submission {
1.119     ng       2488:     my ($returnhash)=@_;
1.46      ng       2489:     my (@string,$timestamp);
1.119     ng       2490:     if ($$returnhash{'version'}) {
1.46      ng       2491: 	my %lasthash=();
                   2492: 	my ($version);
1.119     ng       2493: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2494: 	    foreach my $key (sort(split(/\:/,
                   2495: 					$$returnhash{$version.':keys'}))) {
                   2496: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2497: 		$timestamp = 
                   2498: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2499: 	    }
                   2500: 	}
1.397     albertel 2501: 	foreach my $key (keys(%lasthash)) {
                   2502: 	    next if ($key !~ /\.submission$/);
                   2503: 
                   2504: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2505: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2506: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2507: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2508: 	}
                   2509:     }
1.397     albertel 2510:     if (!@string) {
                   2511: 	$string[0] =
1.398     albertel 2512: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2513:     }
                   2514:     return (\@string,\$timestamp);
1.38      ng       2515: }
1.35      ng       2516: 
1.44      ng       2517: #--- High light keywords, with style choosen by user.
1.38      ng       2518: sub keywords_highlight {
1.44      ng       2519:     my $string    = shift;
1.257     albertel 2520:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2521:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2522:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2523:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2524:     foreach my $keyword (@keylist) {
                   2525: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2526:     }
                   2527:     return $string;
1.38      ng       2528: }
1.36      ng       2529: 
1.44      ng       2530: #--- Called from submission routine
1.38      ng       2531: sub processHandGrade {
1.41      ng       2532:     my ($request) = shift;
1.324     albertel 2533:     my $symb   = &get_symb($request);
                   2534:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2535:     my $button = $env{'form.gradeOpt'};
                   2536:     my $ngrade = $env{'form.NCT'};
                   2537:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2538:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2539:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2540: 
1.44      ng       2541:     if ($button eq 'Save & Next') {
                   2542: 	my $ctr = 0;
                   2543: 	while ($ctr < $ngrade) {
1.257     albertel 2544: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2545: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2546: 	    if ($errorflag eq 'no_score') {
                   2547: 		$ctr++;
                   2548: 		next;
                   2549: 	    }
1.104     albertel 2550: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2551: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2552: 		$ctr++;
                   2553: 		next;
                   2554: 	    }
1.257     albertel 2555: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2556: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2557: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2558:             my ($feedurl,$showsymb) =
                   2559: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2560: 	    my $messagetail;
1.62      albertel 2561: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2562: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2563: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2564: 		$subject.=' ['.$restitle.']';
1.44      ng       2565: 		my (@msgnum) = split(/,/,$includemsg);
                   2566: 		foreach (@msgnum) {
1.257     albertel 2567: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2568: 		}
1.80      ng       2569: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2570: 		if ($env{'form.withgrades'.$ctr}) {
                   2571: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2572: 		    $messagetail = " for <a href=\"".
1.418     albertel 2573: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2574: 		}
                   2575: 		$msgstatus = 
                   2576:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2577: 						     $message.$messagetail,
1.418     albertel 2578:                                                      undef,$feedurl,undef,
1.386     raeburn  2579:                                                      undef,undef,$showsymb,
                   2580:                                                      $restitle);
                   2581: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2582: 				$msgstatus);
1.44      ng       2583: 	    }
1.257     albertel 2584: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2585: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2586: 		foreach my $collabstr (@collabstrs) {
                   2587: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2588: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2589: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2590: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2591: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2592: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2593: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2594: 			    next;
1.418     albertel 2595: 			} elsif ($message ne '') {
                   2596: 			    my ($baseurl,$showsymb) = 
                   2597: 				&get_feedurl_and_symb($symb,$collaborator,
                   2598: 						      $udom);
                   2599: 			    if ($env{'form.withgrades'.$ctr}) {
                   2600: 				$messagetail = " for <a href=\"".
1.386     raeburn  2601:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2602: 			    }
1.418     albertel 2603: 			    $msgstatus = 
                   2604: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2605: 			}
1.44      ng       2606: 		    }
                   2607: 		}
                   2608: 	    }
                   2609: 	    $ctr++;
                   2610: 	}
                   2611:     }
                   2612: 
1.257     albertel 2613:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2614: 	# Keywords sorted in alphabatical order
1.257     albertel 2615: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2616: 	my %keyhash = ();
1.257     albertel 2617: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2618: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2619: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2620: 	$env{'form.keywords'} = join(' ',@keywords);
                   2621: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2622: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2623: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2624: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2625: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2626: 
                   2627: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2628: 	# New messages are saved in env for the next student.
1.119     ng       2629: 	# All messages are saved in nohist_handgrade.db
                   2630: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2631: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2632: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2633: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2634: 		$idx++;
                   2635: 	    }
                   2636: 	    $ctr++;
1.41      ng       2637: 	}
1.119     ng       2638: 	$ctr = 0;
                   2639: 	while ($ctr < $ngrade) {
1.257     albertel 2640: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2641: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2642: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2643: 		$idx++;
                   2644: 	    }
                   2645: 	    $ctr++;
1.41      ng       2646: 	}
1.257     albertel 2647: 	$env{'form.savemsgN'} = --$idx;
                   2648: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2649: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2650: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2651:     }
1.44      ng       2652:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2653:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2654:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2655: 	my ($ctr,$total) = (0,0);
                   2656: 	while ($ctr < $ngrade) {
1.257     albertel 2657: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2658: 	    $ctr++;
                   2659: 	}
1.257     albertel 2660: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2661: 	$ctr = 0;
                   2662: 	while ($ctr < $total) {
1.257     albertel 2663: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2664: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2665: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2666: 	    &submission($request,$ctr,$total-1);
1.41      ng       2667: 	    $ctr++;
                   2668: 	}
                   2669: 	return '';
                   2670:     }
1.36      ng       2671: 
1.121     ng       2672: # Go directly to grade student - from submission or link from chart page
1.120     ng       2673:     if ($button eq 'Grade Student') {
1.324     albertel 2674: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2675: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2676: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2677: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2678: 	&submission($request,0,0);
                   2679: 	return '';
                   2680:     }
                   2681: 
1.44      ng       2682:     # Get the next/previous one or group of students
1.257     albertel 2683:     my $firststu = $env{'form.unamedom0'};
                   2684:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2685:     my $ctr = 2;
1.41      ng       2686:     while ($laststu eq '') {
1.257     albertel 2687: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2688: 	$ctr++;
                   2689: 	$laststu = $firststu if ($ctr > $ngrade);
                   2690:     }
1.44      ng       2691: 
1.41      ng       2692:     my (@parsedlist,@nextlist);
                   2693:     my ($nextflg) = 0;
1.524     raeburn  2694:     foreach my $item (sort 
1.294     albertel 2695: 	     {
                   2696: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2697: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2698: 		 }
                   2699: 		 return $a cmp $b;
                   2700: 	     } (keys(%$fullname))) {
1.41      ng       2701: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2702: 	    push(@parsedlist,$item);
1.41      ng       2703: 	}
1.524     raeburn  2704: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2705: 	if ($button eq 'Previous') {
1.524     raeburn  2706: 	    last if ($item eq $firststu);
                   2707: 	    push(@parsedlist,$item);
1.41      ng       2708: 	}
                   2709:     }
                   2710:     $ctr = 0;
                   2711:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2712:     my ($partlist) = &response_type($symb);
1.41      ng       2713:     foreach my $student (@parsedlist) {
1.257     albertel 2714: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2715: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2716: 	
                   2717: 	if ($submitonly eq 'queued') {
                   2718: 	    my %queue_status = 
                   2719: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2720: 							$udom,$uname);
                   2721: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2722: 	}
                   2723: 
1.156     albertel 2724: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2725: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2726: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2727: 	    my $submitted = 0;
1.248     albertel 2728: 	    my $ungraded = 0;
                   2729: 	    my $incorrect = 0;
1.524     raeburn  2730: 	    foreach my $item (keys(%status)) {
                   2731: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2732: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2733: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2734: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2735: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2736: 		    $submitted = 0;
                   2737: 		}
1.41      ng       2738: 	    }
1.156     albertel 2739: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2740: 				     $submitonly eq 'incorrect' ||
                   2741: 				     $submitonly eq 'graded'));
1.248     albertel 2742: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2743: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2744: 	}
1.524     raeburn  2745: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2746: 	last if ($ctr == $ntstu);
1.41      ng       2747: 	$ctr++;
                   2748:     }
1.36      ng       2749: 
1.41      ng       2750:     $ctr = 0;
                   2751:     my $total = scalar(@nextlist)-1;
1.39      ng       2752: 
1.524     raeburn  2753:     foreach (sort(@nextlist)) {
1.41      ng       2754: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2755: 	$env{'form.student'}  = $uname;
                   2756: 	$env{'form.userdom'}  = $udom;
                   2757: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2758: 	&submission($request,$ctr,$total);
                   2759: 	$ctr++;
                   2760:     }
                   2761:     if ($total < 0) {
1.485     albertel 2762: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2763: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2764: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2765: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2766: 	$request->print($the_end);
                   2767:     }
                   2768:     return '';
1.38      ng       2769: }
1.36      ng       2770: 
1.44      ng       2771: #---- Save the score and award for each student, if changed
1.38      ng       2772: sub saveHandGrade {
1.324     albertel 2773:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2774:     my @version_parts;
1.104     albertel 2775:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2776: 					   $env{'request.course.id'});
1.104     albertel 2777:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2778:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2779:     my @parts_graded;
1.77      ng       2780:     my %newrecord  = ();
                   2781:     my ($pts,$wgt) = ('','');
1.269     raeburn  2782:     my %aggregate = ();
                   2783:     my $aggregateflag = 0;
1.301     albertel 2784:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2785:     foreach my $new_part (@parts) {
1.337     banghart 2786: 	#collaborator ($submi may vary for different parts
1.259     banghart 2787: 	if ($submitter && $new_part ne $part) { next; }
                   2788: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2789: 	if ($dropMenu eq 'excused') {
1.259     banghart 2790: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2791: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2792: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2793: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2794: 		}
1.364     banghart 2795: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2796: 	    }
1.125     ng       2797: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2798: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2799: 	    foreach my $key (keys(%record)) {
1.259     banghart 2800: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2801: 	    }
1.259     banghart 2802: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2803: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2804:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2805: 
                   2806:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2807: 					       [$new_part]);
                   2808:             my $aggtries =$totaltries;
1.269     raeburn  2809:             if ($last_resets{$new_part}) {
1.270     albertel 2810:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2811: 					   $new_part);
1.269     raeburn  2812:             }
1.270     albertel 2813: 
                   2814:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2815:             if ($aggtries > 0) {
1.327     albertel 2816:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2817:                 $aggregateflag = 1;
                   2818:             }
1.125     ng       2819: 	} elsif ($dropMenu eq '') {
1.259     banghart 2820: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2821: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2822: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2823: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2824: 		next;
                   2825: 	    }
1.259     banghart 2826: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2827: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2828: 	    my $partial= $pts/$wgt;
1.259     banghart 2829: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2830: 		#do not update score for part if not changed.
1.346     banghart 2831:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2832: 		next;
1.251     banghart 2833: 	    } else {
1.524     raeburn  2834: 	        push(@parts_graded,$new_part);
1.153     albertel 2835: 	    }
1.259     banghart 2836: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2837: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2838: 	    }
1.259     banghart 2839: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2840: 	    if ($partial == 0) {
1.153     albertel 2841: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2842: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2843: 		}
1.41      ng       2844: 	    } else {
1.153     albertel 2845: 		if ($record{$reckey} ne 'correct_by_override') {
                   2846: 		    $newrecord{$reckey} = 'correct_by_override';
                   2847: 		}
                   2848: 	    }	    
                   2849: 	    if ($submitter && 
1.259     banghart 2850: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2851: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2852: 	    }
1.259     banghart 2853: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2854: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2855: 	}
1.259     banghart 2856: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2857: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2858: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2859: 	        $dropMenu eq 'reset status')
                   2860: 	   {
1.524     raeburn  2861: 	    push(@version_parts,$new_part);
1.259     banghart 2862: 	}
1.41      ng       2863:     }
1.301     albertel 2864:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2865:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2866: 
1.344     albertel 2867:     if (%newrecord) {
                   2868:         if (@version_parts) {
1.364     banghart 2869:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2870:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2871: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2872: 	    foreach my $new_part (@version_parts) {
                   2873: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2874: 				$new_part,\%newrecord);
                   2875: 	    }
1.259     banghart 2876:         }
1.44      ng       2877: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2878: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2879: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2880: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2881:     }
1.269     raeburn  2882:     if ($aggregateflag) {
                   2883:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2884: 			      $cdom,$cnum);
1.269     raeburn  2885:     }
1.301     albertel 2886:     return ('',$pts,$wgt);
1.36      ng       2887: }
1.322     albertel 2888: 
1.380     albertel 2889: sub check_and_remove_from_queue {
                   2890:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2891:     my @ungraded_parts;
                   2892:     foreach my $part (@{$parts}) {
                   2893: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2894: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2895: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2896: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2897: 		) {
                   2898: 	    push(@ungraded_parts, $part);
                   2899: 	}
                   2900:     }
                   2901:     if ( !@ungraded_parts ) {
                   2902: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2903: 					       $cnum,$domain,$stuname);
                   2904:     }
                   2905: }
                   2906: 
1.337     banghart 2907: sub handback_files {
                   2908:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2909:     my $portfolio_root = '/userfiles/portfolio';
1.359     www      2910:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2911: 
                   2912:     my @part_response_id = &flatten_responseType($responseType);
                   2913:     foreach my $part_response_id (@part_response_id) {
                   2914:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2915: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2916:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2917:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2918:                 my $file_counter = 1;
1.367     albertel 2919: 		my $file_msg;
1.337     banghart 2920:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2921:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2922:                     my ($directory,$answer_file) = 
                   2923:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2924:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2925: 		        &file_name_version_ext($answer_file);
1.355     banghart 2926: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2927:                     my $getpropath = 1;
                   2928: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2929: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2930:                     # fix file name
                   2931:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2932:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2933:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2934:             	                                $save_file_name);
1.337     banghart 2935:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2936:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2937:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2938:                     } else {
1.360     banghart 2939:                         # mark the file as read only
                   2940:                         my @files = ($save_file_name);
1.372     albertel 2941:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2942:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2943: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2944: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2945: 			}
                   2946:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2947: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2948: 
1.337     banghart 2949:                     }
                   2950:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2951:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2952:                     $file_counter++;
                   2953:                 }
1.367     albertel 2954: 		my $subject = "File Handed Back by Instructor ";
                   2955: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2956: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2957: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2958: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2959: 		my ($feedurl,$showsymb) = 
                   2960: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2961:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2962: 		my $msgstatus = 
                   2963:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2964: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2965:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2966:             }
                   2967:         }
1.338     banghart 2968:     return;
1.337     banghart 2969: }
                   2970: 
1.418     albertel 2971: sub get_feedurl_and_symb {
                   2972:     my ($symb,$uname,$udom) = @_;
                   2973:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2974:     $url = &Apache::lonnet::clutter($url);
                   2975:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2976: 					$symb,$udom,$uname);
                   2977:     if ($encrypturl =~ /^yes$/i) {
                   2978: 	&Apache::lonenc::encrypted(\$url,1);
                   2979: 	&Apache::lonenc::encrypted(\$symb,1);
                   2980:     }
                   2981:     return ($url,$symb);
                   2982: }
                   2983: 
1.313     banghart 2984: sub get_submitted_files {
                   2985:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2986:     my @files;
                   2987:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2988:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2989:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2990:     	    push(@files,$file_url.$file);
                   2991:         }
                   2992:     }
                   2993:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2994:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2995:     }
                   2996:     return (\@files);
                   2997: }
1.322     albertel 2998: 
1.269     raeburn  2999: # ----------- Provides number of tries since last reset.
                   3000: sub get_num_tries {
                   3001:     my ($record,$last_reset,$part) = @_;
                   3002:     my $timestamp = '';
                   3003:     my $num_tries = 0;
                   3004:     if ($$record{'version'}) {
                   3005:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3006:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3007:                 $timestamp = $$record{$version.':timestamp'};
                   3008:                 if ($timestamp > $last_reset) {
                   3009:                     $num_tries ++;
                   3010:                 } else {
                   3011:                     last;
                   3012:                 }
                   3013:             }
                   3014:         }
                   3015:     }
                   3016:     return $num_tries;
                   3017: }
                   3018: 
                   3019: # ----------- Determine decrements required in aggregate totals 
                   3020: sub decrement_aggs {
                   3021:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3022:     my %decrement = (
                   3023:                         attempts => 0,
                   3024:                         users => 0,
                   3025:                         correct => 0
                   3026:                     );
                   3027:     $decrement{'attempts'} = $aggtries;
                   3028:     if ($solvedstatus =~ /^correct/) {
                   3029:         $decrement{'correct'} = 1;
                   3030:     }
                   3031:     if ($aggtries == $totaltries) {
                   3032:         $decrement{'users'} = 1;
                   3033:     }
1.524     raeburn  3034:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3035:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3036:     }
                   3037:     return;
                   3038: }
                   3039: 
                   3040: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3041: sub get_last_resets {
1.270     albertel 3042:     my ($symb,$courseid,$partids) =@_;
                   3043:     my %last_resets;
1.269     raeburn  3044:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3045:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3046:     my @keys;
                   3047:     foreach my $part (@{$partids}) {
                   3048: 	push(@keys,"$symb\0$part\0resettime");
                   3049:     }
                   3050:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3051: 				     $cdom,$cname);
                   3052:     foreach my $part (@{$partids}) {
                   3053: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3054:     }
1.270     albertel 3055:     return %last_resets;
1.269     raeburn  3056: }
                   3057: 
1.251     banghart 3058: # ----------- Handles creating versions for portfolio files as answers
                   3059: sub version_portfiles {
1.343     banghart 3060:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3061:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3062:     my @returned_keys;
1.255     banghart 3063:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3064:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3065:     foreach my $key (keys(%$record)) {
1.259     banghart 3066:         my $new_portfiles;
1.263     banghart 3067:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3068:             my @versioned_portfiles;
1.367     albertel 3069:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3070:             foreach my $file (@portfiles) {
1.306     banghart 3071:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3072:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3073: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3074: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3075:                 my $getpropath = 1;    
                   3076:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3077:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3078:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3079:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3080:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3081:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3082:                         [$directory.$new_answer],
1.306     banghart 3083:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3084:                 }
1.252     banghart 3085:             }
1.343     banghart 3086:             $$record{$key} = join(',',@versioned_portfiles);
                   3087:             push(@returned_keys,$key);
1.251     banghart 3088:         }
                   3089:     } 
1.343     banghart 3090:     return (@returned_keys);   
1.305     banghart 3091: }
                   3092: 
1.307     banghart 3093: sub get_next_version {
1.341     banghart 3094:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3095:     my $version;
                   3096:     foreach my $row (@$dir_list) {
                   3097:         my ($file) = split(/\&/,$row,2);
                   3098:         my ($file_name,$file_version,$file_ext) =
                   3099: 	    &file_name_version_ext($file);
                   3100:         if (($file_name eq $answer_name) && 
                   3101: 	    ($file_ext eq $answer_ext)) {
                   3102:                 # gets here if filename and extension match, regardless of version
                   3103:                 if ($file_version ne '') {
                   3104:                 # a versioned file is found  so save it for later
                   3105:                 if ($file_version > $version) {
                   3106: 		    $version = $file_version;
                   3107: 	        }
                   3108:             }
                   3109:         }
                   3110:     } 
                   3111:     $version ++;
                   3112:     return($version);
                   3113: }
                   3114: 
1.305     banghart 3115: sub version_selected_portfile {
1.306     banghart 3116:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3117:     my ($answer_name,$answer_ver,$answer_ext) =
                   3118:         &file_name_version_ext($file_name);
                   3119:     my $new_answer;
                   3120:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3121:     if($env{'form.copy'} eq '-1') {
                   3122:         $new_answer = 'problem getting file';
                   3123:     } else {
                   3124:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3125:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3126:                             $stu_name,$domain,'copy',
                   3127: 		        '/portfolio'.$directory.$new_answer);
                   3128:     }    
                   3129:     return ($new_answer);
1.251     banghart 3130: }
                   3131: 
1.304     albertel 3132: sub file_name_version_ext {
                   3133:     my ($file)=@_;
                   3134:     my @file_parts = split(/\./, $file);
                   3135:     my ($name,$version,$ext);
                   3136:     if (@file_parts > 1) {
                   3137: 	$ext=pop(@file_parts);
                   3138: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3139: 	    $version=pop(@file_parts);
                   3140: 	}
                   3141: 	$name=join('.',@file_parts);
                   3142:     } else {
                   3143: 	$name=join('.',@file_parts);
                   3144:     }
                   3145:     return($name,$version,$ext);
                   3146: }
                   3147: 
1.44      ng       3148: #--------------------------------------------------------------------------------------
                   3149: #
                   3150: #-------------------------- Next few routines handles grading by section or whole class
                   3151: #
                   3152: #--- Javascript to handle grading by section or whole class
1.42      ng       3153: sub viewgrades_js {
                   3154:     my ($request) = shift;
                   3155: 
1.41      ng       3156:     $request->print(<<VIEWJAVASCRIPT);
                   3157: <script type="text/javascript" language="javascript">
1.45      ng       3158:    function writePoint(partid,weight,point) {
1.125     ng       3159: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3160: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3161: 	if (point == "textval") {
1.125     ng       3162: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3163: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   3164: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       3165: 		var resetbox = false;
                   3166: 		for (var i=0; i<radioButton.length; i++) {
                   3167: 		    if (radioButton[i].checked) {
                   3168: 			textbox.value = i;
                   3169: 			resetbox = true;
                   3170: 		    }
                   3171: 		}
                   3172: 		if (!resetbox) {
                   3173: 		    textbox.value = "";
                   3174: 		}
                   3175: 		return;
                   3176: 	    }
1.109     matthew  3177: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3178: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3179: 				   ") greater than the weight for the part. Accept?");
                   3180: 		if (resp == false) {
                   3181: 		    textbox.value = "";
                   3182: 		    return;
                   3183: 		}
                   3184: 	    }
1.42      ng       3185: 	    for (var i=0; i<radioButton.length; i++) {
                   3186: 		radioButton[i].checked=false;
1.109     matthew  3187: 		if (parseFloat(point) == i) {
1.42      ng       3188: 		    radioButton[i].checked=true;
                   3189: 		}
                   3190: 	    }
1.41      ng       3191: 
1.42      ng       3192: 	} else {
1.125     ng       3193: 	    textbox.value = parseFloat(point);
1.42      ng       3194: 	}
1.41      ng       3195: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3196: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3197: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3198: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3199: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3200: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3201: 	    if (saveval != "correct") {
                   3202: 		scorename.value = point;
1.43      ng       3203: 		if (selname[0].selected != true) {
                   3204: 		    selname[0].selected = true;
                   3205: 		}
1.42      ng       3206: 	    }
                   3207: 	}
1.125     ng       3208: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3209:     }
                   3210: 
                   3211:     function writeRadText(partid,weight) {
1.125     ng       3212: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3213: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3214:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3215: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3216: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3217: 	    for (var i=0; i<radioButton.length; i++) {
                   3218: 		radioButton[i].checked=false;
                   3219: 
                   3220: 	    }
                   3221: 	    textbox.value = "";
                   3222: 
                   3223: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3224: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3225: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3226: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3227: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3228: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3229: 		if ((saveval != "correct") || override) {
1.42      ng       3230: 		    scorename.value = "";
1.125     ng       3231: 		    if (selval[1].selected) {
                   3232: 			selname[1].selected = true;
                   3233: 		    } else {
                   3234: 			selname[2].selected = true;
                   3235: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3236: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3237: 		    }
1.42      ng       3238: 		}
                   3239: 	    }
1.43      ng       3240: 	} else {
                   3241: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3242: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3243: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3244: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3245: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3246: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3247: 		if ((saveval != "correct") || override) {
1.125     ng       3248: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3249: 		    selname[0].selected = true;
                   3250: 		}
                   3251: 	    }
                   3252: 	}	    
1.42      ng       3253:     }
                   3254: 
                   3255:     function changeSelect(partid,user) {
1.125     ng       3256: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3257: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3258: 	var point  = textbox.value;
1.125     ng       3259: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3260: 
1.109     matthew  3261: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3262: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3263: 	    textbox.value = "";
                   3264: 	    return;
                   3265: 	}
1.109     matthew  3266: 	if (parseFloat(point) > parseFloat(weight)) {
                   3267: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3268: 			       ") greater than the weight of the part. Accept?");
                   3269: 	    if (resp == false) {
                   3270: 		textbox.value = "";
                   3271: 		return;
                   3272: 	    }
                   3273: 	}
1.42      ng       3274: 	selval[0].selected = true;
                   3275:     }
                   3276: 
                   3277:     function changeOneScore(partid,user) {
1.125     ng       3278: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3279: 	if (selval[1].selected || selval[2].selected) {
                   3280: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3281: 	    if (selval[2].selected) {
                   3282: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3283: 	    }
1.269     raeburn  3284:         }
1.42      ng       3285:     }
                   3286: 
                   3287:     function resetEntry(numpart) {
                   3288: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3289: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3290: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3291: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3292: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3293: 	    for (var i=0; i<radioButton.length; i++) {
                   3294: 		radioButton[i].checked=false;
                   3295: 
                   3296: 	    }
                   3297: 	    textbox.value = "";
                   3298: 	    selval[0].selected = true;
                   3299: 
                   3300: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3301: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3302: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3303: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3304: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3305: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3306: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3307: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3308: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3309: 		if (saveselval == "excused") {
1.43      ng       3310: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3311: 		} else {
1.43      ng       3312: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3313: 		}
                   3314: 	    }
1.41      ng       3315: 	}
1.42      ng       3316:     }
                   3317: 
1.41      ng       3318: </script>
                   3319: VIEWJAVASCRIPT
1.42      ng       3320: }
                   3321: 
1.44      ng       3322: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3323: sub viewgrades {
                   3324:     my ($request) = shift;
                   3325:     &viewgrades_js($request);
1.41      ng       3326: 
1.324     albertel 3327:     my ($symb) = &get_symb($request);
1.168     albertel 3328:     #need to make sure we have the correct data for later EXT calls, 
                   3329:     #thus invalidate the cache
                   3330:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3331:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3332:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3333:     &Apache::lonnet::clear_EXT_cache_status();
                   3334: 
1.398     albertel 3335:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3336:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3337: 
                   3338:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3339:     $result.=&jscriptNform($symb);
1.41      ng       3340: 
1.44      ng       3341:     #beginning of class grading form
1.442     banghart 3342:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3343:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3344: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3345: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3346: 	&build_section_inputs().
1.257     albertel 3347: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3348: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3349: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3350: 
1.126     ng       3351:     my $sectionClass;
1.430     banghart 3352:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3353:     if ($env{'form.section'} eq 'all') {
1.485     albertel 3354: 	$sectionClass='Class';
1.257     albertel 3355:     } elsif ($env{'form.section'} eq 'none') {
1.485     albertel 3356: 	$sectionClass='Students in no Section';
1.52      albertel 3357:     } else {
1.485     albertel 3358: 	$sectionClass='Students in Section(s) [_1]';
1.52      albertel 3359:     }
1.485     albertel 3360:     $result.=
                   3361: 	'<h3>'.
                   3362: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
1.474     albertel 3363:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3364:     #radio buttons/text box for assigning points for a section or class.
                   3365:     #handles different parts of a problem
1.375     albertel 3366:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3367:     my %weight = ();
                   3368:     my $ctsparts = 0;
1.45      ng       3369:     my %seen = ();
1.375     albertel 3370:     my @part_response_id = &flatten_responseType($responseType);
                   3371:     foreach my $part_response_id (@part_response_id) {
                   3372:     	my ($partid,$respid) = @{ $part_response_id };
                   3373: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3374: 	next if $seen{$partid};
                   3375: 	$seen{$partid}++;
1.375     albertel 3376: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3377: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3378: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3379: 
1.324     albertel 3380: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3381: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3382: 	my $ctr = 0;
1.42      ng       3383: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3384: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3385: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3386: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3387: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3388: 	    $ctr++;
                   3389: 	}
1.485     albertel 3390: 	$radio.='</tr></table>';
                   3391: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3392: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3393: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3394: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.485     albertel 3395: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3396: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3397: 		$weight{$partid}.')"> '.
1.401     albertel 3398: 	    '<option selected="selected"> </option>'.
1.485     albertel 3399: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3400: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3401: 	    '</select></td>'.
                   3402:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3403: 	$line.='<input type="hidden" name="partid_'.
                   3404: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3405: 	$line.='<input type="hidden" name="weight_'.
                   3406: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3407: 
                   3408: 	$result.=
                   3409: 	    &Apache::loncommon::start_data_table_row()."\n".
                   3410: 	    &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).
                   3411: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3412: 	$ctsparts++;
1.41      ng       3413:     }
1.474     albertel 3414:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3415: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3416:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3417: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3418: 
1.44      ng       3419:     #table listing all the students in a section/class
                   3420:     #header of table
1.485     albertel 3421:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
                   3422: 			 $section_display).'</h3>';
1.474     albertel 3423:     $result.= &Apache::loncommon::start_data_table().
                   3424: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 3425: 	'<th>'.&mt('No.').'</th>'.
1.474     albertel 3426: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3427:     my (@parts) = sort(&getpartlist($symb));
                   3428:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3429:     my @partids = ();
1.41      ng       3430:     foreach my $part (@parts) {
                   3431: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3432: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3433: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3434: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3435:         push(@partids,$partid);
1.324     albertel 3436: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3437: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3438: 	    $result.='<th>'.
                   3439: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3440: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3441: 	    next;
1.485     albertel 3442: 	    
1.207     albertel 3443: 	} else {
1.485     albertel 3444: 	    if ($display =~ /Problem Status/) {
                   3445: 		my $grade_status_mt = &mt('Grade Status');
                   3446: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3447: 	    }
                   3448: 	    my $part_mt = &mt('Part:');
                   3449: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3450: 	}
1.485     albertel 3451: 
1.474     albertel 3452: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3453:     }
1.474     albertel 3454:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3455: 
1.270     albertel 3456:     my %last_resets = 
                   3457: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3458: 
1.41      ng       3459:     #get info for each student
1.44      ng       3460:     #list all the students - with points and grade status
1.257     albertel 3461:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3462:     my $ctr = 0;
1.294     albertel 3463:     foreach (sort 
                   3464: 	     {
                   3465: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3466: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3467: 		 }
                   3468: 		 return $a cmp $b;
                   3469: 	     } (keys(%$fullname))) {
1.126     ng       3470: 	$ctr++;
1.324     albertel 3471: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3472: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3473:     }
1.474     albertel 3474:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3475:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3476:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3477: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3478:     if (scalar(%$fullname) eq 0) {
                   3479: 	my $colspan=3+scalar(@parts);
1.433     banghart 3480: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3481:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3482: 	$result='<span class="LC_warning">'.
1.485     albertel 3483: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3484: 	        $section_display, $stu_status).
1.433     banghart 3485: 	    '</span>';
1.96      albertel 3486:     }
1.324     albertel 3487:     $result.=&show_grading_menu_form($symb);
1.41      ng       3488:     return $result;
                   3489: }
                   3490: 
1.44      ng       3491: #--- call by previous routine to display each student
1.41      ng       3492: sub viewstudentgrade {
1.324     albertel 3493:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3494:     my ($uname,$udom) = split(/:/,$student);
                   3495:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3496:     my %aggregates = (); 
1.474     albertel 3497:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3498: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3499: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3500: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3501: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3502: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3503:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3504:     foreach my $apart (@$parts) {
                   3505: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3506: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3507:         $result.='<td align="center">';
1.269     raeburn  3508:         my ($aggtries,$totaltries);
                   3509:         unless (exists($aggregates{$part})) {
1.270     albertel 3510: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3511: 
                   3512: 	    $aggtries = $totaltries;
1.269     raeburn  3513:             if ($$last_resets{$part}) {  
1.270     albertel 3514:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3515: 					   $part);
                   3516:             }
1.269     raeburn  3517:             $result.='<input type="hidden" name="'.
                   3518:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3519:             $result.='<input type="hidden" name="'.
                   3520:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3521:             $aggregates{$part} = 1;
                   3522:         }
1.41      ng       3523: 	if ($type eq 'awarded') {
1.320     albertel 3524: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3525: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3526: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3527: 	    $result.='<input type="text" name="'.
1.89      albertel 3528: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3529: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3530: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3531: 	} elsif ($type eq 'solved') {
                   3532: 	    my ($status,$foo)=split(/_/,$score,2);
                   3533: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3534: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3535: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3536: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3537: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3538: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3539: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3540: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3541: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3542: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3543: 	} else {
                   3544: 	    $result.='<input type="hidden" name="'.
                   3545: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3546: 		    "\n";
1.233     albertel 3547: 	    $result.='<input type="text" name="'.
1.122     ng       3548: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3549: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3550: 	}
                   3551:     }
1.474     albertel 3552:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3553:     return $result;
1.38      ng       3554: }
                   3555: 
1.44      ng       3556: #--- change scores for all the students in a section/class
                   3557: #    record does not get update if unchanged
1.38      ng       3558: sub editgrades {
1.41      ng       3559:     my ($request) = @_;
                   3560: 
1.324     albertel 3561:     my $symb=&get_symb($request);
1.433     banghart 3562:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3563:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3564:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3565:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3566: 
1.477     albertel 3567:     my $result= &Apache::loncommon::start_data_table().
                   3568: 	&Apache::loncommon::start_data_table_header_row().
                   3569: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3570: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3571:     my %scoreptr = (
                   3572: 		    'correct'  =>'correct_by_override',
                   3573: 		    'incorrect'=>'incorrect_by_override',
                   3574: 		    'excused'  =>'excused',
                   3575: 		    'ungraded' =>'ungraded_attempted',
                   3576: 		    'nothing'  => '',
                   3577: 		    );
1.257     albertel 3578:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3579: 
1.44      ng       3580:     my (@partid);
                   3581:     my %weight = ();
1.54      albertel 3582:     my %columns = ();
1.44      ng       3583:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3584: 
1.324     albertel 3585:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3586:     my $header;
1.257     albertel 3587:     while ($ctr < $env{'form.totalparts'}) {
                   3588: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3589: 	push(@partid,$partid);
1.257     albertel 3590: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3591: 	$ctr++;
1.54      albertel 3592:     }
1.324     albertel 3593:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3594:     foreach my $partid (@partid) {
1.478     albertel 3595: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3596: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3597: 	$columns{$partid}=2;
                   3598: 	foreach my $stores (@parts) {
                   3599: 	    my ($part,$type) = &split_part_type($stores);
                   3600: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3601: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3602: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3603: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3604: 	    $display =~ s/Number of Attempts/Tries/;
1.478     albertel 3605: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
                   3606: 		'<th align="center">'.&mt('New '.$display).'</th>';
1.54      albertel 3607: 	    $columns{$partid}+=2;
                   3608: 	}
                   3609:     }
                   3610:     foreach my $partid (@partid) {
1.324     albertel 3611: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3612: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3613: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3614: 	    '</th>';
1.54      albertel 3615: 
1.44      ng       3616:     }
1.477     albertel 3617:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3618: 	&Apache::loncommon::start_data_table_header_row().
                   3619: 	$header.
                   3620: 	&Apache::loncommon::end_data_table_header_row();
                   3621:     my @noupdate;
1.126     ng       3622:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3623:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3624: 	my $line;
1.257     albertel 3625: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3626: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3627: 	my %newrecord;
                   3628: 	my $updateflag = 0;
1.281     albertel 3629: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3630: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3631: 	if (!&canmodify($usec)) {
1.126     ng       3632: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3633: 	    push(@noupdate,
1.478     albertel 3634: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3635: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3636: 	    next;
                   3637: 	}
1.269     raeburn  3638:         my %aggregate = ();
                   3639:         my $aggregateflag = 0;
1.281     albertel 3640: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3641: 	foreach (@partid) {
1.257     albertel 3642: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3643: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3644: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3645: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3646: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3647: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3648: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3649: 	    my $score;
                   3650: 	    if ($partial eq '') {
1.257     albertel 3651: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3652: 	    } elsif ($partial > 0) {
                   3653: 		$score = 'correct_by_override';
                   3654: 	    } elsif ($partial == 0) {
                   3655: 		$score = 'incorrect_by_override';
                   3656: 	    }
1.257     albertel 3657: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3658: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3659: 
1.292     albertel 3660: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3661: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3662: 	    if ($dropMenu eq 'reset status' &&
                   3663: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3664: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3665: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3666: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3667: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3668: 		$updateflag = 1;
1.269     raeburn  3669:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3670:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3671:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3672:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3673:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3674:                     $aggregateflag = 1;
                   3675:                 }
1.139     albertel 3676: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3677: 		$updateflag = 1;
                   3678: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3679: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3680: 		$rec_update++;
1.125     ng       3681: 	    }
                   3682: 
1.93      albertel 3683: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3684: 		'<td align="center">'.$awarded.
                   3685: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3686: 
1.54      albertel 3687: 
                   3688: 	    my $partid=$_;
                   3689: 	    foreach my $stores (@parts) {
                   3690: 		my ($part,$type) = &split_part_type($stores);
                   3691: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3692: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3693: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3694: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3695: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3696: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3697: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3698: 		    $updateflag=1;
                   3699: 		}
1.93      albertel 3700: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3701: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3702: 	    }
1.44      ng       3703: 	}
1.477     albertel 3704: 	$line.="\n";
1.301     albertel 3705: 
                   3706: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3707: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3708: 
1.44      ng       3709: 	if ($updateflag) {
                   3710: 	    $count++;
1.257     albertel 3711: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3712: 				    $udom,$uname);
1.301     albertel 3713: 
                   3714: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3715: 					      $cnum,$udom,$uname)) {
                   3716: 		# need to figure out if should be in queue.
                   3717: 		my %record =  
                   3718: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3719: 					     $udom,$uname);
                   3720: 		my $all_graded = 1;
                   3721: 		my $none_graded = 1;
                   3722: 		foreach my $part (@parts) {
                   3723: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3724: 			$all_graded = 0;
                   3725: 		    } else {
                   3726: 			$none_graded = 0;
                   3727: 		    }
                   3728: 		}
                   3729: 
                   3730: 		if ($all_graded || $none_graded) {
                   3731: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3732: 							   $symb,$cdom,$cnum,
                   3733: 							   $udom,$uname);
                   3734: 		}
                   3735: 	    }
                   3736: 
1.477     albertel 3737: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3738: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3739: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3740: 	    $updateCtr++;
1.93      albertel 3741: 	} else {
1.477     albertel 3742: 	    push(@noupdate,
                   3743: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3744: 	    $noupdateCtr++;
1.44      ng       3745: 	}
1.269     raeburn  3746:         if ($aggregateflag) {
                   3747:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3748: 				  $cdom,$cnum);
1.269     raeburn  3749:         }
1.93      albertel 3750:     }
1.477     albertel 3751:     if (@noupdate) {
1.126     ng       3752: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3753: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3754: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3755: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3756: 	    &mt('No Changes Occurred For the Students Below').
                   3757: 	    '</td>'.
1.477     albertel 3758: 	    &Apache::loncommon::end_data_table_row();
                   3759: 	foreach my $line (@noupdate) {
                   3760: 	    $result.=
                   3761: 		&Apache::loncommon::start_data_table_row().
                   3762: 		$line.
                   3763: 		&Apache::loncommon::end_data_table_row();
                   3764: 	}
1.44      ng       3765:     }
1.477     albertel 3766:     $result .= &Apache::loncommon::end_data_table().
                   3767: 	&show_grading_menu_form($symb);
1.478     albertel 3768:     my $msg = '<p><b>'.
                   3769: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3770: 	    $rec_update,$count).'</b><br />'.
                   3771: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3772: 	'</b></p>';
1.44      ng       3773:     return $title.$msg.$result;
1.5       albertel 3774: }
1.54      albertel 3775: 
                   3776: sub split_part_type {
                   3777:     my ($partstr) = @_;
                   3778:     my ($temp,@allparts)=split(/_/,$partstr);
                   3779:     my $type=pop(@allparts);
1.439     albertel 3780:     my $part=join('_',@allparts);
1.54      albertel 3781:     return ($part,$type);
                   3782: }
                   3783: 
1.44      ng       3784: #------------- end of section for handling grading by section/class ---------
                   3785: #
                   3786: #----------------------------------------------------------------------------
                   3787: 
1.5       albertel 3788: 
1.44      ng       3789: #----------------------------------------------------------------------------
                   3790: #
                   3791: #-------------------------- Next few routines handles grading by csv upload
                   3792: #
                   3793: #--- Javascript to handle csv upload
1.27      albertel 3794: sub csvupload_javascript_reverse_associate {
1.246     albertel 3795:     my $error1=&mt('You need to specify the username or ID');
                   3796:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3797:   return(<<ENDPICK);
                   3798:   function verify(vf) {
                   3799:     var foundsomething=0;
                   3800:     var founduname=0;
1.243     albertel 3801:     var foundID=0;
1.27      albertel 3802:     for (i=0;i<=vf.nfields.value;i++) {
                   3803:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3804:       if (i==0 && tw!=0) { foundID=1; }
                   3805:       if (i==1 && tw!=0) { founduname=1; }
                   3806:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3807:     }
1.246     albertel 3808:     if (founduname==0 && foundID==0) {
                   3809: 	alert('$error1');
                   3810: 	return;
1.27      albertel 3811:     }
                   3812:     if (foundsomething==0) {
1.246     albertel 3813: 	alert('$error2');
                   3814: 	return;
1.27      albertel 3815:     }
                   3816:     vf.submit();
                   3817:   }
                   3818:   function flip(vf,tf) {
                   3819:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3820:     var i;
                   3821:     for (i=0;i<=vf.nfields.value;i++) {
                   3822:       //can not pick the same destination field for both name and domain
                   3823:       if (((i ==0)||(i ==1)) && 
                   3824:           ((tf==0)||(tf==1)) && 
                   3825:           (i!=tf) &&
                   3826:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3827:         eval('vf.f'+i+'.selectedIndex=0;')
                   3828:       }
                   3829:     }
                   3830:   }
                   3831: ENDPICK
                   3832: }
                   3833: 
                   3834: sub csvupload_javascript_forward_associate {
1.246     albertel 3835:     my $error1=&mt('You need to specify the username or ID');
                   3836:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3837:   return(<<ENDPICK);
                   3838:   function verify(vf) {
                   3839:     var foundsomething=0;
                   3840:     var founduname=0;
1.243     albertel 3841:     var foundID=0;
1.27      albertel 3842:     for (i=0;i<=vf.nfields.value;i++) {
                   3843:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3844:       if (tw==1) { foundID=1; }
                   3845:       if (tw==2) { founduname=1; }
                   3846:       if (tw>3) { foundsomething=1; }
1.27      albertel 3847:     }
1.246     albertel 3848:     if (founduname==0 && foundID==0) {
                   3849: 	alert('$error1');
                   3850: 	return;
1.27      albertel 3851:     }
                   3852:     if (foundsomething==0) {
1.246     albertel 3853: 	alert('$error2');
                   3854: 	return;
1.27      albertel 3855:     }
                   3856:     vf.submit();
                   3857:   }
                   3858:   function flip(vf,tf) {
                   3859:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3860:     var i;
                   3861:     //can not pick the same destination field twice
                   3862:     for (i=0;i<=vf.nfields.value;i++) {
                   3863:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3864:         eval('vf.f'+i+'.selectedIndex=0;')
                   3865:       }
                   3866:     }
                   3867:   }
                   3868: ENDPICK
                   3869: }
                   3870: 
1.26      albertel 3871: sub csvuploadmap_header {
1.324     albertel 3872:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3873:     my $javascript;
1.257     albertel 3874:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3875: 	$javascript=&csvupload_javascript_reverse_associate();
                   3876:     } else {
                   3877: 	$javascript=&csvupload_javascript_forward_associate();
                   3878:     }
1.45      ng       3879: 
1.324     albertel 3880:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3881:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3882:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3883:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3884:     $request->print(<<ENDPICK);
1.26      albertel 3885: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3886: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3887: $result
1.326     albertel 3888: <hr />
1.26      albertel 3889: <h3>Identify fields</h3>
                   3890: Total number of records found in file: $distotal <hr />
                   3891: Enter as many fields as you can. The system will inform you and bring you back
                   3892: to this page if the data selected is insufficient to run your class.<hr />
                   3893: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3894: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3895: <input type="hidden" name="associate"  value="" />
                   3896: <input type="hidden" name="phase"      value="three" />
                   3897: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3898: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3899: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3900: <input type="hidden" name="upfile_associate" 
1.257     albertel 3901:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3902: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3903: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3904: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3905: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3906: <hr />
                   3907: <script type="text/javascript" language="Javascript">
                   3908: $javascript
                   3909: </script>
                   3910: ENDPICK
1.118     ng       3911:     return '';
1.26      albertel 3912: 
                   3913: }
                   3914: 
                   3915: sub csvupload_fields {
1.324     albertel 3916:     my ($symb) = @_;
                   3917:     my (@parts) = &getpartlist($symb);
1.243     albertel 3918:     my @fields=(['ID','Student ID'],
                   3919: 		['username','Student Username'],
                   3920: 		['domain','Student Domain']);
1.324     albertel 3921:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3922:     foreach my $part (sort(@parts)) {
                   3923: 	my @datum;
                   3924: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3925: 	my $name=$part;
                   3926: 	if  (!$display) { $display = $name; }
                   3927: 	@datum=($name,$display);
1.244     albertel 3928: 	if ($name=~/^stores_(.*)_awarded/) {
                   3929: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3930: 	}
1.41      ng       3931: 	push(@fields,\@datum);
                   3932:     }
                   3933:     return (@fields);
1.26      albertel 3934: }
                   3935: 
                   3936: sub csvuploadmap_footer {
1.41      ng       3937:     my ($request,$i,$keyfields) =@_;
                   3938:     $request->print(<<ENDPICK);
1.26      albertel 3939: </table>
                   3940: <input type="hidden" name="nfields" value="$i" />
                   3941: <input type="hidden" name="keyfields" value="$keyfields" />
                   3942: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3943: </form>
                   3944: ENDPICK
                   3945: }
                   3946: 
1.283     albertel 3947: sub checkforfile_js {
1.86      ng       3948:     my $result =<<CSVFORMJS;
                   3949: <script type="text/javascript" language="javascript">
                   3950:     function checkUpload(formname) {
                   3951: 	if (formname.upfile.value == "") {
                   3952: 	    alert("Please use the browse button to select a file from your local directory.");
                   3953: 	    return false;
                   3954: 	}
                   3955: 	formname.submit();
                   3956:     }
                   3957:     </script>
                   3958: CSVFORMJS
1.283     albertel 3959:     return $result;
                   3960: }
                   3961: 
                   3962: sub upcsvScores_form {
                   3963:     my ($request) = shift;
1.324     albertel 3964:     my ($symb)=&get_symb($request);
1.283     albertel 3965:     if (!$symb) {return '';}
                   3966:     my $result=&checkforfile_js();
1.257     albertel 3967:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3968:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3969:     $result.=$table;
1.326     albertel 3970:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3971:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3972:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3973: 	'.</b></td></tr>'."\n";
                   3974:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3975:     my $upload=&mt("Upload Scores");
1.86      ng       3976:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3977:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3978:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3979:     $result.=<<ENDUPFORM;
1.106     albertel 3980: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3981: <input type="hidden" name="symb" value="$symb" />
                   3982: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3983: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3984: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3985: $upfile_select
1.370     www      3986: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3987: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3988: </form>
                   3989: ENDUPFORM
1.370     www      3990:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3991:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3992:     .'</td></tr></table>'."\n";
1.86      ng       3993:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3994:     $result.=&show_grading_menu_form($symb);
1.86      ng       3995:     return $result;
                   3996: }
                   3997: 
                   3998: 
1.26      albertel 3999: sub csvuploadmap {
1.41      ng       4000:     my ($request)= @_;
1.324     albertel 4001:     my ($symb)=&get_symb($request);
1.41      ng       4002:     if (!$symb) {return '';}
1.72      ng       4003: 
1.41      ng       4004:     my $datatoken;
1.257     albertel 4005:     if (!$env{'form.datatoken'}) {
1.41      ng       4006: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4007:     } else {
1.257     albertel 4008: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4009: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4010:     }
1.41      ng       4011:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4012:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4013:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4014:     my ($i,$keyfields);
                   4015:     if (@records) {
1.324     albertel 4016: 	my @fields=&csvupload_fields($symb);
1.45      ng       4017: 
1.257     albertel 4018: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4019: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4020: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4021: 							  \@fields);
                   4022: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4023: 	    chop($keyfields);
                   4024: 	} else {
                   4025: 	    unshift(@fields,['none','']);
                   4026: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4027: 							    \@fields);
1.311     banghart 4028:             foreach my $rec (@records) {
                   4029:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4030:                 if (%temp) {
                   4031:                     $keyfields=join(',',sort(keys(%temp)));
                   4032:                     last;
                   4033:                 }
                   4034:             }
1.41      ng       4035: 	}
                   4036:     }
                   4037:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4038:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4039: 
1.41      ng       4040:     return '';
1.27      albertel 4041: }
                   4042: 
1.246     albertel 4043: sub csvuploadoptions {
1.41      ng       4044:     my ($request)= @_;
1.324     albertel 4045:     my ($symb)=&get_symb($request);
1.257     albertel 4046:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4047:     my $ignore=&mt('Ignore First Line');
                   4048:     $request->print(<<ENDPICK);
                   4049: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4050: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4051: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4052: <!--
1.246     albertel 4053: <p>
                   4054: <label>
                   4055:    <input type="checkbox" name="show_full_results" />
                   4056:    Show a table of all changes
                   4057: </label>
                   4058: </p>
1.302     albertel 4059: -->
1.246     albertel 4060: <p>
                   4061: <label>
                   4062:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4063:    Overwrite any existing score
                   4064: </label>
                   4065: </p>
                   4066: ENDPICK
                   4067:     my %fields=&get_fields();
                   4068:     if (!defined($fields{'domain'})) {
1.257     albertel 4069: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4070: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4071:     }
1.257     albertel 4072:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4073: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4074: 	my $cleankey=$1;
                   4075: 	if ($cleankey eq 'command') { next; }
                   4076: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4077: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4078:     }
                   4079:     # FIXME do a check for any duplicated user ids...
                   4080:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4081:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4082: <hr /></form>'."\n");
1.324     albertel 4083:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4084:     return '';
                   4085: }
                   4086: 
                   4087: sub get_fields {
                   4088:     my %fields;
1.257     albertel 4089:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4090:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4091: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4092: 	    if ($env{'form.f'.$i} ne 'none') {
                   4093: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4094: 	    }
                   4095: 	} else {
1.257     albertel 4096: 	    if ($env{'form.f'.$i} ne 'none') {
                   4097: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4098: 	    }
                   4099: 	}
1.27      albertel 4100:     }
1.246     albertel 4101:     return %fields;
                   4102: }
                   4103: 
                   4104: sub csvuploadassign {
                   4105:     my ($request)= @_;
1.324     albertel 4106:     my ($symb)=&get_symb($request);
1.246     albertel 4107:     if (!$symb) {return '';}
1.345     bowersj2 4108:     my $error_msg = '';
1.246     albertel 4109:     &Apache::loncommon::load_tmp_file($request);
                   4110:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4111:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4112:     my %fields=&get_fields();
1.41      ng       4113:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4114:     my $courseid=$env{'request.course.id'};
1.97      albertel 4115:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4116:     my @notallowed;
1.41      ng       4117:     my @skipped;
                   4118:     my $countdone=0;
                   4119:     foreach my $grade (@gradedata) {
                   4120: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4121: 	my $domain;
                   4122: 	if ($entries{$fields{'domain'}}) {
                   4123: 	    $domain=$entries{$fields{'domain'}};
                   4124: 	} else {
1.257     albertel 4125: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4126: 	}
1.243     albertel 4127: 	$domain=~s/\s//g;
1.41      ng       4128: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4129: 	$username=~s/\s//g;
1.243     albertel 4130: 	if (!$username) {
                   4131: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4132: 	    $id=~s/\s//g;
1.243     albertel 4133: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4134: 	    $username=$ids{$id};
                   4135: 	}
1.41      ng       4136: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4137: 	    my $id=$entries{$fields{'ID'}};
                   4138: 	    $id=~s/\s//g;
                   4139: 	    if ($id) {
                   4140: 		push(@skipped,"$id:$domain");
                   4141: 	    } else {
                   4142: 		push(@skipped,"$username:$domain");
                   4143: 	    }
1.41      ng       4144: 	    next;
                   4145: 	}
1.108     albertel 4146: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4147: 	if (!&canmodify($usec)) {
                   4148: 	    push(@notallowed,"$username:$domain");
                   4149: 	    next;
                   4150: 	}
1.244     albertel 4151: 	my %points;
1.41      ng       4152: 	my %grades;
                   4153: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4154: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4155: 		$dest eq 'domain') { next; }
                   4156: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4157: 	    if ($dest=~/stores_(.*)_points/) {
                   4158: 		my $part=$1;
                   4159: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4160: 					      $symb,$domain,$username);
1.345     bowersj2 4161:                 if ($wgt) {
                   4162:                     $entries{$fields{$dest}}=~s/\s//g;
                   4163:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4164:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4165:                                           : 'correct_by_override';
1.345     bowersj2 4166:                     $grades{"resource.$part.awarded"}=$pcr;
                   4167:                     $grades{"resource.$part.solved"}=$award;
                   4168:                     $points{$part}=1;
                   4169:                 } else {
                   4170:                     $error_msg = "<br />" .
                   4171:                         &mt("Some point values were assigned"
                   4172:                             ." for problems with a weight "
                   4173:                             ."of zero. These values were "
                   4174:                             ."ignored.");
                   4175:                 }
1.244     albertel 4176: 	    } else {
                   4177: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4178: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4179: 		my $store_key=$dest;
                   4180: 		$store_key=~s/^stores/resource/;
                   4181: 		$store_key=~s/_/\./g;
                   4182: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4183: 	    }
1.41      ng       4184: 	}
1.508     www      4185: 	if (! %grades) { 
                   4186:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4187:         } else {
                   4188: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4189: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4190: 					   $env{'request.course.id'},
                   4191: 					   $domain,$username);
1.508     www      4192: 	   if ($result eq 'ok') {
                   4193: 	      $request->print('.');
                   4194: 	   } else {
                   4195: 	      $request->print("<p><span class=\"LC_error\">".
                   4196:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4197:                                   "$username:$domain",$result)."</span></p>");
                   4198: 	   }
                   4199: 	   $request->rflush();
                   4200: 	   $countdone++;
                   4201:         }
1.41      ng       4202:     }
1.508     www      4203:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
1.41      ng       4204:     if (@skipped) {
1.508     www      4205: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
1.106     albertel 4206: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4207:     }
                   4208:     if (@notallowed) {
1.508     www      4209: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
1.106     albertel 4210: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4211:     }
1.106     albertel 4212:     $request->print("<br />\n");
1.324     albertel 4213:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4214:     return $error_msg;
1.26      albertel 4215: }
1.44      ng       4216: #------------- end of section for handling csv file upload ---------
                   4217: #
                   4218: #-------------------------------------------------------------------
                   4219: #
1.122     ng       4220: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4221: #
                   4222: #--- Select a page/sequence and a student to grade
1.68      ng       4223: sub pickStudentPage {
                   4224:     my ($request) = shift;
                   4225: 
                   4226:     $request->print(<<LISTJAVASCRIPT);
                   4227: <script type="text/javascript" language="javascript">
                   4228: 
                   4229: function checkPickOne(formname) {
1.76      ng       4230:     if (radioSelection(formname.student) == null) {
1.68      ng       4231: 	alert("Please select the student you wish to grade.");
                   4232: 	return;
                   4233:     }
1.125     ng       4234:     ptr = pullDownSelection(formname.selectpage);
                   4235:     formname.page.value = formname["page"+ptr].value;
                   4236:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4237:     formname.submit();
                   4238: }
                   4239: 
                   4240: </script>
                   4241: LISTJAVASCRIPT
1.118     ng       4242:     &commonJSfunctions($request);
1.324     albertel 4243:     my ($symb) = &get_symb($request);
1.257     albertel 4244:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4245:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4246:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4247: 
1.398     albertel 4248:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4249: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4250: 
1.80      ng       4251:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4252:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4253:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4254: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4255: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4256:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4257:     my $ctr=0;
1.68      ng       4258:     foreach (@$titles) {
                   4259: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4260: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4261: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4262: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4263: 	$ctr++;
1.68      ng       4264:     }
1.485     albertel 4265:     $select.= '</select>';
                   4266:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
                   4267: 
1.70      ng       4268:     $ctr=0;
                   4269:     foreach (@$titles) {
                   4270: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4271: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4272: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4273: 	$ctr++;
                   4274:     }
1.72      ng       4275:     $result.='<input type="hidden" name="page" />'."\n".
                   4276: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4277: 
1.485     albertel 4278:     my $options =
                   4279: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4280: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
                   4281:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
                   4282: 
                   4283:     $options =
                   4284: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4285: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4286: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
                   4287:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
1.432     banghart 4288:     
                   4289:     $result.=&build_section_inputs();
1.442     banghart 4290:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4291:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4292: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4293: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4294: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4295: 
1.485     albertel 4296:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
                   4297: 			  '<input type="text" name="CODE" value="" />').
                   4298: 			      '<br />'."\n";
1.382     albertel 4299: 
1.80      ng       4300:     $result.='&nbsp;<input type="button" '.
1.485     albertel 4301: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
1.72      ng       4302: 
1.68      ng       4303:     $request->print($result);
                   4304: 
1.485     albertel 4305:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4306: 	&Apache::loncommon::start_data_table().
                   4307: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4308: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4309: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4310: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4311: 	'<th>'.&nameUserString('header').'</th>'.
                   4312: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4313:  
1.76      ng       4314:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4315:     my $ptr = 1;
1.294     albertel 4316:     foreach my $student (sort 
                   4317: 			 {
                   4318: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4319: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4320: 			     }
                   4321: 			     return $a cmp $b;
                   4322: 			 } (keys(%$fullname))) {
1.68      ng       4323: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4324: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4325:                                   : '</td>');
1.126     ng       4326: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4327: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4328: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4329: 	$studentTable.=
                   4330: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4331:                          : '');
1.68      ng       4332: 	$ptr++;
                   4333:     }
1.484     albertel 4334:     if ($ptr%2 == 0) {
                   4335: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4336: 	    &Apache::loncommon::end_data_table_row();
                   4337:     }
                   4338:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4339:     $studentTable.='<input type="button" '.
1.485     albertel 4340: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.68      ng       4341: 
1.324     albertel 4342:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4343:     $request->print($studentTable);
                   4344: 
                   4345:     return '';
                   4346: }
                   4347: 
                   4348: sub getSymbMap {
1.132     bowersj2 4349:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4350: 
                   4351:     my %symbx = ();
                   4352:     my @titles = ();
1.117     bowersj2 4353:     my $minder = 0;
                   4354: 
                   4355:     # Gather every sequence that has problems.
1.240     albertel 4356:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4357: 					       1,0,1);
1.117     bowersj2 4358:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4359: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4360: 	    my $title = $minder.'.'.
                   4361: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4362: 	    push(@titles, $title); # minder in case two titles are identical
                   4363: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4364: 	    $minder++;
1.241     albertel 4365: 	}
1.68      ng       4366:     }
                   4367:     return \@titles,\%symbx;
                   4368: }
                   4369: 
1.72      ng       4370: #
                   4371: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4372: sub displayPage {
                   4373:     my ($request) = shift;
                   4374: 
1.324     albertel 4375:     my ($symb) = &get_symb($request);
1.257     albertel 4376:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4377:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4378:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4379:     my $pageTitle = $env{'form.page'};
1.103     albertel 4380:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4381:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4382:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4383: 
                   4384:     #need to make sure we have the correct data for later EXT calls, 
                   4385:     #thus invalidate the cache
                   4386:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4387:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4388:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4389:     &Apache::lonnet::clear_EXT_cache_status();
                   4390: 
1.103     albertel 4391:     if (!&canview($usec)) {
1.485     albertel 4392: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4393: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4394: 	return;
                   4395:     }
1.398     albertel 4396:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4397:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4398: 	'</h3>'."\n";
1.500     albertel 4399:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4400:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4401: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4402:     } else {
                   4403: 	delete($env{'form.CODE'});
                   4404:     }
1.71      ng       4405:     &sub_page_js($request);
                   4406:     $request->print($result);
                   4407: 
1.132     bowersj2 4408:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4409:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4410:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4411:     if (!$map) {
1.485     albertel 4412: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4413: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4414: 	return; 
                   4415:     }
1.68      ng       4416:     my $iterator = $navmap->getIterator($map->map_start(),
                   4417: 					$map->map_finish());
                   4418: 
1.71      ng       4419:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4420: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4421: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4422: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4423: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4424: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4425: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4426: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4427: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4428: 
1.382     albertel 4429:     if (defined($env{'form.CODE'})) {
                   4430: 	$studentTable.=
                   4431: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4432:     }
1.381     albertel 4433:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4434: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4435: 
1.485     albertel 4436:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4437: 	&Apache::loncommon::start_data_table().
                   4438: 	&Apache::loncommon::start_data_table_header_row().
                   4439: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4440: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4441: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4442: 
1.329     albertel 4443:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4444:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4445:     $iterator->next(); # skip the first BEGIN_MAP
                   4446:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4447:     while ($depth > 0) {
1.68      ng       4448:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4449:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4450: 
1.385     albertel 4451:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4452: 	    my $parts = $curRes->parts();
1.68      ng       4453:             my $title = $curRes->compTitle();
1.71      ng       4454: 	    my $symbx = $curRes->symb();
1.484     albertel 4455: 	    $studentTable.=
                   4456: 		&Apache::loncommon::start_data_table_row().
                   4457: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4458: 		(scalar(@{$parts}) == 1 ? '' 
                   4459: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4460: 							scalar(@{$parts}))
                   4461: 		 ).
                   4462: 		 '</td>';
1.71      ng       4463: 	    $studentTable.='<td valign="top">';
1.382     albertel 4464: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4465: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4466: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4467: 					     undef,'both',\%form);
1.71      ng       4468: 	    } else {
1.382     albertel 4469: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4470: 		$companswer =~ s|<form(.*?)>||g;
                   4471: 		$companswer =~ s|</form>||g;
1.71      ng       4472: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4473: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4474: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4475: #		}
1.116     ng       4476: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.485     albertel 4477: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
1.71      ng       4478: 	    }
                   4479: 
1.257     albertel 4480: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4481: 
1.257     albertel 4482: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4483: 		if ($record{'version'} eq '') {
1.485     albertel 4484: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4485: 		} else {
1.116     ng       4486: 		    my %responseType = ();
                   4487: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4488: 			my @responseIds =$curRes->responseIds($partid);
                   4489: 			my @responseType =$curRes->responseType($partid);
                   4490: 			my %responseIds;
                   4491: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4492: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4493: 			}
                   4494: 			$responseType{$partid} = \%responseIds;
1.116     ng       4495: 		    }
1.148     albertel 4496: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4497: 
1.71      ng       4498: 		}
1.257     albertel 4499: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4500: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4501: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4502: 									$env{'request.course.id'},
1.71      ng       4503: 									'','.submission');
                   4504:  
                   4505: 	    }
1.103     albertel 4506: 	    if (&canmodify($usec)) {
                   4507: 		foreach my $partid (@{$parts}) {
                   4508: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4509: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4510: 		    $question++;
                   4511: 		}
1.196     albertel 4512: 		$prob++;
1.71      ng       4513: 	    }
                   4514: 	    $studentTable.='</td></tr>';
1.68      ng       4515: 
1.103     albertel 4516: 	}
1.68      ng       4517:         $curRes = $iterator->next();
                   4518:     }
                   4519: 
1.485     albertel 4520:     $studentTable.='</table>'."\n".
                   4521: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4522: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4523: 	'</form>'."\n";
1.324     albertel 4524:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4525:     $request->print($studentTable);
                   4526: 
                   4527:     return '';
1.119     ng       4528: }
                   4529: 
                   4530: sub displaySubByDates {
1.148     albertel 4531:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4532:     my $isCODE=0;
1.335     albertel 4533:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4534:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4535:     my $studentTable=&Apache::loncommon::start_data_table().
                   4536: 	&Apache::loncommon::start_data_table_header_row().
                   4537: 	'<th>'.&mt('Date/Time').'</th>'.
                   4538: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4539: 	'<th>'.&mt('Submission').'</th>'.
                   4540: 	'<th>'.&mt('Status').'</th>'.
                   4541: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4542:     my ($version);
                   4543:     my %mark;
1.148     albertel 4544:     my %orders;
1.119     ng       4545:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4546:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4547: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4548:     }
1.335     albertel 4549: 
                   4550:     my $interaction;
1.525     raeburn  4551:     my $no_increment = 1;
1.119     ng       4552:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4553: 	my $timestamp = 
                   4554: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4555: 	if (exists($$record{$version.':resource.0.version'})) {
                   4556: 	    $interaction = $$record{$version.':resource.0.version'};
                   4557: 	}
                   4558: 
                   4559: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4560: 		             : "$version:resource");
1.467     albertel 4561: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4562: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4563: 	if ($isCODE) {
                   4564: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4565: 	}
1.119     ng       4566: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4567: 	my @displaySub = ();
                   4568: 	foreach my $partid (@{$parts}) {
1.335     albertel 4569: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4570: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4571: 	    
                   4572: 
1.122     ng       4573: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4574: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4575: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4576: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4577: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4578: 
                   4579: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4580: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4581: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4582: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4583: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4584: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4585: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4586: 		    } else {
1.467     albertel 4587: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4588: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4589: 		    }
1.335     albertel 4590: 		    my $responseType=($isTask ? 'Task'
                   4591:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4592: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4593: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4594: 			$orders{$partid}->{$responseId}=
1.525     raeburn  4595: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
                   4596:                                        $no_increment);
1.148     albertel 4597: 		    }
1.147     albertel 4598: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4599: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4600: 		}
                   4601: 	    }
1.335     albertel 4602: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4603: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4604: 				    $$record{"$where.$partid.checkedin"},
                   4605: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4606: 					'<br />';
1.335     albertel 4607: 	    }
                   4608: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4609: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4610: 		    lc($$record{"$where.$partid.award"}).' '.
                   4611: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4612: 		    '<br />';
                   4613: 	    }
1.335     albertel 4614: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4615: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4616: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4617: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4618: 		$displaySub[2].=
                   4619: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4620: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4621: 	    }
                   4622: 	}
                   4623: 	# needed because old essay regrader has not parts info
                   4624: 	if (exists $$record{"$version:resource.regrader"}) {
                   4625: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4626: 	}
                   4627: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4628: 	if ($displaySub[2]) {
1.467     albertel 4629: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4630: 	}
1.467     albertel 4631: 	$studentTable.='&nbsp;</td>'.
                   4632: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4633:     }
1.467     albertel 4634:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4635:     return $studentTable;
1.71      ng       4636: }
                   4637: 
                   4638: sub updateGradeByPage {
                   4639:     my ($request) = shift;
                   4640: 
1.257     albertel 4641:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4642:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4643:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4644:     my $pageTitle = $env{'form.page'};
1.103     albertel 4645:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4646:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4647:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4648:     if (!&canmodify($usec)) {
1.526     raeburn  4649: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4650: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4651: 	return;
                   4652:     }
1.398     albertel 4653:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4654:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4655: 	'</h3>'."\n";
1.70      ng       4656: 
1.68      ng       4657:     $request->print($result);
                   4658: 
1.132     bowersj2 4659:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4660:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4661:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4662:     if (!$map) {
1.527     raeburn  4663: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4664: 	my ($symb)=&get_symb($request);
                   4665: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4666: 	return; 
                   4667:     }
1.71      ng       4668:     my $iterator = $navmap->getIterator($map->map_start(),
                   4669: 					$map->map_finish());
1.70      ng       4670: 
1.484     albertel 4671:     my $studentTable=
                   4672: 	&Apache::loncommon::start_data_table().
                   4673: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4674: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4675: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4676: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4677: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4678: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4679: 
                   4680:     $iterator->next(); # skip the first BEGIN_MAP
                   4681:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4682:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4683:     while ($depth > 0) {
1.71      ng       4684:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4685:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4686: 
1.385     albertel 4687:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4688: 	    my $parts = $curRes->parts();
1.71      ng       4689:             my $title = $curRes->compTitle();
                   4690: 	    my $symbx = $curRes->symb();
1.484     albertel 4691: 	    $studentTable.=
                   4692: 		&Apache::loncommon::start_data_table_row().
                   4693: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4694: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4695:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4696: 		.')').'</td>';
1.71      ng       4697: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4698: 
                   4699: 	    my %newrecord=();
                   4700: 	    my @displayPts=();
1.269     raeburn  4701:             my %aggregate = ();
                   4702:             my $aggregateflag = 0;
1.71      ng       4703: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4704: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4705: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4706: 
1.257     albertel 4707: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4708: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4709: 		my $partial = $newpts/$wgt;
                   4710: 		my $score;
                   4711: 		if ($partial > 0) {
                   4712: 		    $score = 'correct_by_override';
1.125     ng       4713: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4714: 		    $score = 'incorrect_by_override';
                   4715: 		}
1.257     albertel 4716: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4717: 		if ($dropMenu eq 'excused') {
1.71      ng       4718: 		    $partial = '';
                   4719: 		    $score = 'excused';
1.125     ng       4720: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4721: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4722: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4723: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4724: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4725: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4726: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4727: 		    $changeflag++;
                   4728: 		    $newpts = '';
1.269     raeburn  4729:                     
                   4730:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4731:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4732:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4733:                     if ($aggtries > 0) {
                   4734:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4735:                         $aggregateflag = 1;
                   4736:                     }
1.71      ng       4737: 		}
1.324     albertel 4738: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4739: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4740: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4741: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4742: 		    '&nbsp;<br />';
1.526     raeburn  4743: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4744: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4745: 		    '&nbsp;<br />';
1.71      ng       4746: 		$question++;
1.380     albertel 4747: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4748: 
1.71      ng       4749: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4750: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4751: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4752: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4753: 
                   4754: 		$changeflag++;
                   4755: 	    }
                   4756: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4757: 		my %record = 
                   4758: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4759: 					     $udom,$uname);
                   4760: 
                   4761: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4762: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4763: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4764: 		    $newrecord{'resource.CODE'} = '';
                   4765: 		}
1.257     albertel 4766: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4767: 					$udom,$uname);
1.382     albertel 4768: 		%record = &Apache::lonnet::restore($symbx,
                   4769: 						   $env{'request.course.id'},
                   4770: 						   $udom,$uname);
1.380     albertel 4771: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4772: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4773: 	    }
1.380     albertel 4774: 	    
1.269     raeburn  4775:             if ($aggregateflag) {
                   4776:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4777:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4778:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4779:             }
1.125     ng       4780: 
1.71      ng       4781: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4782: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4783: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4784: 
1.196     albertel 4785: 	    $prob++;
1.68      ng       4786: 	}
1.71      ng       4787:         $curRes = $iterator->next();
1.68      ng       4788:     }
1.98      albertel 4789: 
1.484     albertel 4790:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4791:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4792:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4793: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4794: 		  $changeflag));
1.76      ng       4795:     $request->print($grademsg.$studentTable);
1.68      ng       4796: 
1.70      ng       4797:     return '';
                   4798: }
                   4799: 
1.72      ng       4800: #-------- end of section for handling grading by page/sequence ---------
                   4801: #
                   4802: #-------------------------------------------------------------------
                   4803: 
1.75      albertel 4804: #--------------------Scantron Grading-----------------------------------
                   4805: #
                   4806: #------ start of section for handling grading by page/sequence ---------
                   4807: 
1.423     albertel 4808: =pod
                   4809: 
                   4810: =head1 Bubble sheet grading routines
                   4811: 
1.424     albertel 4812:   For this documentation:
                   4813: 
                   4814:    'scanline' refers to the full line of characters
                   4815:    from the file that we are parsing that represents one entire sheet
                   4816: 
                   4817:    'bubble line' refers to the data
                   4818:    representing the line of bubbles that are on the physical bubble sheet
                   4819: 
                   4820: 
                   4821: The overall process is that a scanned in bubble sheet data is uploaded
                   4822: into a course. When a user wants to grade, they select a
                   4823: sequence/folder of resources, a file of bubble sheet info, and pick
                   4824: one of the predefined configurations for what each scanline looks
                   4825: like.
                   4826: 
                   4827: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4828: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4829: because too light bubbling), 'double bubble' (each bubble line should
                   4830: have no more that one letter picked), invalid or duplicated CODE,
                   4831: invalid student ID
                   4832: 
                   4833: If the CODE option is used that determines the randomization of the
                   4834: homework problems, either way the student ID is looked up into a
                   4835: username:domain.
                   4836: 
                   4837: During the validation phase the instructor can choose to skip scanlines. 
                   4838: 
1.435     foxr     4839: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4840: 
                   4841:   scantron_original_filename (unmodified original file)
                   4842:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4843:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4844: 
                   4845: Also there is a separate hash nohist_scantrondata that contains extra
                   4846: correction information that isn't representable in the bubble sheet
                   4847: file (see &scantron_getfile() for more information)
                   4848: 
                   4849: After all scanlines are either valid, marked as valid or skipped, then
                   4850: foreach line foreach problem in the picked sequence, an ssi request is
                   4851: made that simulates a user submitting their selected letter(s) against
                   4852: the homework problem.
1.423     albertel 4853: 
                   4854: =over 4
                   4855: 
                   4856: 
                   4857: 
                   4858: =item defaultFormData
                   4859: 
                   4860:   Returns html hidden inputs used to hold context/default values.
                   4861: 
                   4862:  Arguments:
                   4863:   $symb - $symb of the current resource 
                   4864: 
                   4865: =cut
1.422     foxr     4866: 
1.81      albertel 4867: sub defaultFormData {
1.324     albertel 4868:     my ($symb)=@_;
1.447     foxr     4869:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4870:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4871:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4872: }
                   4873: 
1.447     foxr     4874: 
1.423     albertel 4875: =pod 
                   4876: 
                   4877: =item getSequenceDropDown
                   4878: 
                   4879:    Return html dropdown of possible sequences to grade
                   4880:  
                   4881:  Arguments:
                   4882:    $symb - $symb of the current resource 
                   4883: 
                   4884: =cut
1.422     foxr     4885: 
1.75      albertel 4886: sub getSequenceDropDown {
1.423     albertel 4887:     my ($symb)=@_;
1.75      albertel 4888:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4889:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4890:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4891:     my $ctr=0;
                   4892:     foreach (@$titles) {
                   4893: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4894: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4895: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4896: 	    '>'.$showtitle.'</option>'."\n";
                   4897: 	$ctr++;
                   4898:     }
                   4899:     $result.= '</select>';
                   4900:     return $result;
                   4901: }
                   4902: 
1.495     albertel 4903: my %bubble_lines_per_response;     # no. bubble lines for each response.
                   4904:                                    # index is "symb.part_id"
                   4905: 
                   4906: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4907: 
1.509     raeburn  4908: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4909:                                    # matchresponse or rankresponse, where 
                   4910:                                    # an individual response can have multiple 
                   4911:                                    # lines
1.503     raeburn  4912: 
                   4913: my %responsetype_per_response;     # responsetype for each response
                   4914: 
1.495     albertel 4915: # Save and restore the bubble lines array to the form env.
                   4916: 
                   4917: 
                   4918: sub save_bubble_lines {
                   4919:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4920: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4921: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4922: 	    $first_bubble_line{$line};
1.503     raeburn  4923:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4924:             $subdivided_bubble_lines{$line};
                   4925:         $env{"form.scantron.responsetype.$line"} =
                   4926:             $responsetype_per_response{$line};
1.495     albertel 4927:     }
                   4928: }
                   4929: 
                   4930: 
                   4931: sub restore_bubble_lines {
                   4932:     my $line = 0;
                   4933:     %bubble_lines_per_response = ();
                   4934:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4935: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4936: 	$bubble_lines_per_response{$line} = $value;
                   4937: 	$first_bubble_line{$line}  =
                   4938: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4939:         $subdivided_bubble_lines{$line} =
                   4940:             $env{"form.scantron.sub_bubblelines.$line"};
                   4941:         $responsetype_per_response{$line} =
                   4942:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4943: 	$line++;
                   4944:     }
                   4945: 
                   4946: }
                   4947: 
                   4948: #  Given the parsed scanline, get the response for 
                   4949: #  'answer' number n:
                   4950: 
                   4951: sub get_response_bubbles {
                   4952:     my ($parsed_line, $response)  = @_;
                   4953: 
                   4954: 
                   4955:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4956:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4957:     
                   4958:     my $selected = "";
                   4959: 
                   4960:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4961: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4962: 	$bubble_line++;
                   4963:     }
                   4964:     return $selected;
                   4965: }
1.423     albertel 4966: 
                   4967: =pod 
                   4968: 
                   4969: =item scantron_filenames
                   4970: 
                   4971:    Returns a list of the scantron files in the current course 
                   4972: 
                   4973: =cut
1.422     foxr     4974: 
1.202     albertel 4975: sub scantron_filenames {
1.257     albertel 4976:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4977:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4978:     my $getpropath = 1;
1.157     albertel 4979:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4980:                                        $getpropath);
1.202     albertel 4981:     my @possiblenames;
1.201     albertel 4982:     foreach my $filename (sort(@files)) {
1.157     albertel 4983: 	($filename)=split(/&/,$filename);
                   4984: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4985: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4986: 	push(@possiblenames,$filename);
                   4987:     }
                   4988:     return @possiblenames;
                   4989: }
                   4990: 
1.423     albertel 4991: =pod 
                   4992: 
                   4993: =item scantron_uploads
                   4994: 
                   4995:    Returns  html drop-down list of scantron files in current course.
                   4996: 
                   4997:  Arguments:
                   4998:    $file2grade - filename to set as selected in the dropdown
                   4999: 
                   5000: =cut
1.422     foxr     5001: 
1.202     albertel 5002: sub scantron_uploads {
1.209     ng       5003:     my ($file2grade) = @_;
1.202     albertel 5004:     my $result=	'<select name="scantron_selectfile">';
                   5005:     $result.="<option></option>";
                   5006:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5007: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5008:     }
                   5009:     $result.="</select>";
                   5010:     return $result;
                   5011: }
                   5012: 
1.423     albertel 5013: =pod 
                   5014: 
                   5015: =item scantron_scantab
                   5016: 
                   5017:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5018:   file.
                   5019: 
                   5020: =cut
1.422     foxr     5021: 
1.82      albertel 5022: sub scantron_scantab {
                   5023:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5024:     $result.='<option></option>'."\n";
1.518     raeburn  5025:     my @lines = &get_scantronformat_file();
                   5026:     if (@lines > 0) {
                   5027:         foreach my $line (@lines) {
                   5028:             next if (($line =~ /^\#/) || ($line eq ''));
                   5029: 	    my ($name,$descrip)=split(/:/,$line);
                   5030: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5031:         }
1.82      albertel 5032:     }
                   5033:     $result.='</select>'."\n";
1.518     raeburn  5034:     return $result;
                   5035: }
                   5036: 
                   5037: =pod
                   5038: 
                   5039: =item get_scantronformat_file
                   5040: 
                   5041:   Returns an array containing lines from the scantron format file for
                   5042:   the domain of the course.
                   5043: 
                   5044:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5045:   lines are from this file.
                   5046: 
                   5047:   Otherwise, if a default.tab has been published in RES space by the 
                   5048:   domainconfig user, lines are from this file.
                   5049: 
                   5050:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5051:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5052: 
1.518     raeburn  5053: =cut
                   5054: 
                   5055: sub get_scantronformat_file {
                   5056:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5057:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5058:     my $gottab = 0;
                   5059:     my @lines;
                   5060:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5061:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5062:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5063:             if ($formatfile ne '-1') {
                   5064:                 @lines = split("\n",$formatfile,-1);
                   5065:                 $gottab = 1;
                   5066:             }
                   5067:         }
                   5068:     }
                   5069:     if (!$gottab) {
                   5070:         my $confname = $cdom.'-domainconfig';
                   5071:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5072:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5073:         if ($formatfile ne '-1') {
                   5074:             @lines = split("\n",$formatfile,-1);
                   5075:             $gottab = 1;
                   5076:         }
                   5077:     }
                   5078:     if (!$gottab) {
1.519     raeburn  5079:         my @domains = &Apache::lonnet::current_machine_domains();
                   5080:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5081:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5082:             @lines = <$fh>;
                   5083:             close($fh);
                   5084:         } else {
                   5085:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5086:             @lines = <$fh>;
                   5087:             close($fh);
                   5088:         }
1.518     raeburn  5089:     }
                   5090:     return @lines;
1.82      albertel 5091: }
                   5092: 
1.423     albertel 5093: =pod 
                   5094: 
                   5095: =item scantron_CODElist
                   5096: 
                   5097:   Returns html drop down of the saved CODE lists from current course,
                   5098:   generated from earlier printings.
                   5099: 
                   5100: =cut
1.422     foxr     5101: 
1.186     albertel 5102: sub scantron_CODElist {
1.257     albertel 5103:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5104:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5105:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5106:     my $namechoice='<option></option>';
1.225     albertel 5107:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5108: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5109: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5110: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5111:     }
                   5112:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5113:     return $namechoice;
                   5114: }
                   5115: 
1.423     albertel 5116: =pod 
                   5117: 
                   5118: =item scantron_CODEunique
                   5119: 
                   5120:   Returns the html for "Each CODE to be used once" radio.
                   5121: 
                   5122: =cut
1.422     foxr     5123: 
1.186     albertel 5124: sub scantron_CODEunique {
1.381     albertel 5125:     my $result='<span style="white-space: nowrap;">
1.272     albertel 5126:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5127:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5128:                 </span>
                   5129:                 <span style="white-space: nowrap;">
1.272     albertel 5130:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5131:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5132:                 </span>';
1.186     albertel 5133:     return $result;
                   5134: }
1.423     albertel 5135: 
                   5136: =pod 
                   5137: 
                   5138: =item scantron_selectphase
                   5139: 
                   5140:   Generates the initial screen to start the bubble sheet process.
                   5141:   Allows for - starting a grading run.
1.424     albertel 5142:              - downloading existing scan data (original, corrected
1.423     albertel 5143:                                                 or skipped info)
                   5144: 
                   5145:              - uploading new scan data
                   5146: 
                   5147:  Arguments:
                   5148:   $r          - The Apache request object
                   5149:   $file2grade - name of the file that contain the scanned data to score
                   5150: 
                   5151: =cut
1.186     albertel 5152: 
1.75      albertel 5153: sub scantron_selectphase {
1.209     ng       5154:     my ($r,$file2grade) = @_;
1.324     albertel 5155:     my ($symb)=&get_symb($r);
1.75      albertel 5156:     if (!$symb) {return '';}
1.423     albertel 5157:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 5158:     my $default_form_data=&defaultFormData($symb);
                   5159:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5160:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5161:     my $format_selector=&scantron_scantab();
1.186     albertel 5162:     my $CODE_selector=&scantron_CODElist();
                   5163:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5164:     my $result;
1.422     foxr     5165: 
1.513     foxr     5166:     $ssi_error = 0;
                   5167: 
1.422     foxr     5168:     # Chunk of form to prompt for a file to grade and how:
                   5169: 
1.489     albertel 5170:     $result.= '
                   5171:     <br />
                   5172:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5173:     <input type="hidden" name="command" value="scantron_warning" />
                   5174:     '.$default_form_data.'
                   5175:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5176:        '.&Apache::loncommon::start_data_table_header_row().'
                   5177:             <th colspan="2">
1.492     albertel 5178:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5179:             </th>
                   5180:        '.&Apache::loncommon::end_data_table_header_row().'
                   5181:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5182:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5183:        '.&Apache::loncommon::end_data_table_row().'
                   5184:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5185:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5186:        '.&Apache::loncommon::end_data_table_row().'
                   5187:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5188:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5189:        '.&Apache::loncommon::end_data_table_row().'
                   5190:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5191:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5192:        '.&Apache::loncommon::end_data_table_row().'
                   5193:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5194:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5195:        '.&Apache::loncommon::end_data_table_row().'
                   5196:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5197: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5198:             <td>
1.492     albertel 5199: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5200:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5201:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5202: 	    </td>
1.489     albertel 5203:        '.&Apache::loncommon::end_data_table_row().'
                   5204:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5205:             <td colspan="2">
1.492     albertel 5206:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
1.162     albertel 5207:             </td>
1.489     albertel 5208:        '.&Apache::loncommon::end_data_table_row().'
                   5209:     '.&Apache::loncommon::end_data_table().'
                   5210:     </form>
                   5211: ';
1.162     albertel 5212:    
                   5213:     $r->print($result);
                   5214: 
1.257     albertel 5215:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5216:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5217: 
1.422     foxr     5218: 	# Chunk of form to prompt for a scantron file upload.
                   5219: 
1.489     albertel 5220:         $r->print('
                   5221:     <br />
                   5222:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5223:        '.&Apache::loncommon::start_data_table_header_row().'
                   5224:             <th>
1.492     albertel 5225:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
1.489     albertel 5226:             </th>
                   5227:        '.&Apache::loncommon::end_data_table_header_row().'
                   5228:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5229:             <td>
1.489     albertel 5230: ');
1.324     albertel 5231:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5232:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5233:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5234:     $r->print('
1.174     albertel 5235:               <script type="text/javascript" language="javascript">
                   5236:     function checkUpload(formname) {
                   5237: 	if (formname.upfile.value == "") {
1.492     albertel 5238: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5239: 	    return false;
                   5240: 	}
                   5241: 	formname.submit();
                   5242:     }
                   5243:               </script>
                   5244: 
1.492     albertel 5245:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5246:                 '.$default_form_data.'
                   5247:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5248:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5249:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5250:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5251:                 <br />
1.492     albertel 5252:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.174     albertel 5253:               </form>
1.492     albertel 5254: ');
1.162     albertel 5255: 
1.489     albertel 5256:         $r->print('
1.162     albertel 5257:             </td>
1.489     albertel 5258:        '.&Apache::loncommon::end_data_table_row().'
                   5259:        '.&Apache::loncommon::end_data_table().'
                   5260: ');
1.162     albertel 5261:     }
1.422     foxr     5262: 
                   5263:     # Chunk of the form that prompts to view a scoring office file,
                   5264:     # corrected file, skipped records in a file.
                   5265: 
1.489     albertel 5266:     $r->print('
                   5267:    <br />
                   5268:    <form action="/adm/grades" name="scantron_download">
                   5269:      '.$default_form_data.'
                   5270:      <input type="hidden" name="command" value="scantron_download" />
                   5271:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5272:        '.&Apache::loncommon::start_data_table_header_row().'
                   5273:               <th>
1.492     albertel 5274:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5275:               </th>
                   5276:        '.&Apache::loncommon::end_data_table_header_row().'
                   5277:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5278:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5279:                 <br />
1.492     albertel 5280:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5281:        '.&Apache::loncommon::end_data_table_row().'
                   5282:      '.&Apache::loncommon::end_data_table().'
                   5283:    </form>
                   5284:    <br />
                   5285: ');
1.162     albertel 5286: 
1.457     banghart 5287:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5288: 
1.528     raeburn  5289:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5290:              $default_form_data."\n".
                   5291:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5292:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5293:              '<th colspan="2">
                   5294:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
                   5295:              '</th>'."\n".
                   5296:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5297:               &Apache::loncommon::start_data_table_row()."\n".
                   5298:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5299:               '<td> '.$sequence_selector.' </td>'.
                   5300:               &Apache::loncommon::end_data_table_row()."\n".
                   5301:               &Apache::loncommon::start_data_table_row()."\n".
                   5302:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5303:               '<td> '.$file_selector.' </td>'."\n".
                   5304:               &Apache::loncommon::end_data_table_row()."\n".
                   5305:               &Apache::loncommon::start_data_table_row()."\n".
                   5306:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5307:               '<td> '.$format_selector.' </td>'."\n".
                   5308:               &Apache::loncommon::end_data_table_row()."\n".
                   5309:               &Apache::loncommon::start_data_table_row()."\n".
                   5310:               '<td colspan="2">'."\n".
                   5311:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
                   5312:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
                   5313:               '</td>'."\n".
                   5314:               &Apache::loncommon::end_data_table_row()."\n".
                   5315:               &Apache::loncommon::end_data_table()."\n".
                   5316:               '</form><br />');
1.457     banghart 5317:     $r->print($grading_menu_button);
1.523     raeburn  5318:     return;
1.75      albertel 5319: }
                   5320: 
1.423     albertel 5321: =pod
                   5322: 
                   5323: =item get_scantron_config
                   5324: 
                   5325:    Parse and return the scantron configuration line selected as a
                   5326:    hash of configuration file fields.
                   5327: 
                   5328:  Arguments:
                   5329:     which - the name of the configuration to parse from the file.
                   5330: 
                   5331: 
                   5332:  Returns:
                   5333:             If the named configuration is not in the file, an empty
                   5334:             hash is returned.
                   5335:     a hash with the fields
                   5336:       name         - internal name for the this configuration setup
                   5337:       description  - text to display to operator that describes this config
                   5338:       CODElocation - if 0 or the string 'none'
                   5339:                           - no CODE exists for this config
                   5340:                      if -1 || the string 'letter'
                   5341:                           - a CODE exists for this config and is
                   5342:                             a string of letters
                   5343:                      Unsupported value (but planned for future support)
                   5344:                           if a positive integer
                   5345:                                - The CODE exists as the first n items from
                   5346:                                  the question section of the form
                   5347:                           if the string 'number'
                   5348:                                - The CODE exists for this config and is
                   5349:                                  a string of numbers
                   5350:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5351:                      the CODE starts
                   5352:       CODElength  - length of the CODE
                   5353:       IDstart     - column where the student ID number starts
                   5354:       IDlength    - length of the student ID info
                   5355:       Qstart      - column where the information from the bubbled
                   5356:                     'questions' start
                   5357:       Qlength     - number of columns comprising a single bubble line from
                   5358:                     the sheet. (usually either 1 or 10)
1.424     albertel 5359:       Qon         - either a single character representing the character used
1.423     albertel 5360:                     to signal a bubble was chosen in the positional setup, or
                   5361:                     the string 'letter' if the letter of the chosen bubble is
                   5362:                     in the final, or 'number' if a number representing the
                   5363:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5364:       Qoff        - the character used to represent that a bubble was
                   5365:                     left blank
1.423     albertel 5366:       PaperID     - if the scanning process generates a unique number for each
                   5367:                     sheet scanned the column that this ID number starts in
                   5368:       PaperIDlength - number of columns that comprise the unique ID number
                   5369:                       for the sheet of paper
1.424     albertel 5370:       FirstName   - column that the first name starts in
1.423     albertel 5371:       FirstNameLength - number of columns that the first name spans
                   5372:  
                   5373:       LastName    - column that the last name starts in
                   5374:       LastNameLength - number of columns that the last name spans
                   5375: 
                   5376: =cut
1.422     foxr     5377: 
1.82      albertel 5378: sub get_scantron_config {
                   5379:     my ($which) = @_;
1.518     raeburn  5380:     my @lines = &get_scantronformat_file();
1.82      albertel 5381:     my %config;
1.157     albertel 5382:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5383:     foreach my $line (@lines) {
1.82      albertel 5384: 	my ($name,$descrip)=split(/:/,$line);
                   5385: 	if ($name ne $which ) { next; }
                   5386: 	chomp($line);
                   5387: 	my @config=split(/:/,$line);
                   5388: 	$config{'name'}=$config[0];
                   5389: 	$config{'description'}=$config[1];
                   5390: 	$config{'CODElocation'}=$config[2];
                   5391: 	$config{'CODEstart'}=$config[3];
                   5392: 	$config{'CODElength'}=$config[4];
                   5393: 	$config{'IDstart'}=$config[5];
                   5394: 	$config{'IDlength'}=$config[6];
                   5395: 	$config{'Qstart'}=$config[7];
1.497     foxr     5396:  	$config{'Qlength'}=$config[8];
1.82      albertel 5397: 	$config{'Qoff'}=$config[9];
                   5398: 	$config{'Qon'}=$config[10];
1.157     albertel 5399: 	$config{'PaperID'}=$config[11];
                   5400: 	$config{'PaperIDlength'}=$config[12];
                   5401: 	$config{'FirstName'}=$config[13];
                   5402: 	$config{'FirstNamelength'}=$config[14];
                   5403: 	$config{'LastName'}=$config[15];
                   5404: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5405: 	last;
                   5406:     }
                   5407:     return %config;
                   5408: }
                   5409: 
1.423     albertel 5410: =pod 
                   5411: 
                   5412: =item username_to_idmap
                   5413: 
                   5414:     creates a hash keyed by student id with values of the corresponding
                   5415:     student username:domain.
                   5416: 
                   5417:   Arguments:
                   5418: 
                   5419:     $classlist - reference to the class list hash. This is a hash
                   5420:                  keyed by student name:domain  whose elements are references
1.424     albertel 5421:                  to arrays containing various chunks of information
1.423     albertel 5422:                  about the student. (See loncoursedata for more info).
                   5423: 
                   5424:   Returns
                   5425:     %idmap - the constructed hash
                   5426: 
                   5427: =cut
                   5428: 
1.82      albertel 5429: sub username_to_idmap {
                   5430:     my ($classlist)= @_;
                   5431:     my %idmap;
                   5432:     foreach my $student (keys(%$classlist)) {
                   5433: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5434: 	    $student;
                   5435:     }
                   5436:     return %idmap;
                   5437: }
1.423     albertel 5438: 
                   5439: =pod
                   5440: 
1.424     albertel 5441: =item scantron_fixup_scanline
1.423     albertel 5442: 
                   5443:    Process a requested correction to a scanline.
                   5444: 
                   5445:   Arguments:
                   5446:     $scantron_config   - hash from &get_scantron_config()
                   5447:     $scan_data         - hash of correction information 
                   5448:                           (see &scantron_getfile())
                   5449:     $line              - existing scanline
                   5450:     $whichline         - line number of the passed in scanline
                   5451:     $field             - type of change to process 
                   5452:                          (either 
                   5453:                           'ID'     -> correct the student ID number
                   5454:                           'CODE'   -> correct the CODE
                   5455:                           'answer' -> fixup the submitted answers)
                   5456:     
                   5457:    $args               - hash of additional info,
                   5458:                           - 'ID' 
                   5459:                                'newid' -> studentID to use in replacement
1.424     albertel 5460:                                           of existing one
1.423     albertel 5461:                           - 'CODE' 
                   5462:                                'CODE_ignore_dup' - set to true if duplicates
                   5463:                                                    should be ignored.
                   5464: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5465:                                         if the existing unfound code should
1.423     albertel 5466:                                         be used as is
                   5467:                           - 'answer'
                   5468:                                'response' - new answer or 'none' if blank
                   5469:                                'question' - the bubble line to change
1.503     raeburn  5470:                                'questionnum' - the question identifier,
                   5471:                                                may include subquestion. 
1.423     albertel 5472: 
                   5473:   Returns:
                   5474:     $line - the modified scanline
                   5475: 
                   5476:   Side effects: 
                   5477:     $scan_data - may be updated
                   5478: 
                   5479: =cut
                   5480: 
1.82      albertel 5481: 
1.157     albertel 5482: sub scantron_fixup_scanline {
                   5483:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5484:     if ($field eq 'ID') {
                   5485: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5486: 	    return ($line,1,'New value too large');
1.157     albertel 5487: 	}
                   5488: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5489: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5490: 				     $args->{'newid'});
                   5491: 	}
                   5492: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5493: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5494: 	if ($args->{'newid'}=~/^\s*$/) {
                   5495: 	    &scan_data($scan_data,"$whichline.user",
                   5496: 		       $args->{'username'}.':'.$args->{'domain'});
                   5497: 	}
1.186     albertel 5498:     } elsif ($field eq 'CODE') {
1.192     albertel 5499: 	if ($args->{'CODE_ignore_dup'}) {
                   5500: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5501: 	}
                   5502: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5503: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5504: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5505: 		return ($line,1,'New CODE value too large');
                   5506: 	    }
                   5507: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5508: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5509: 	    }
                   5510: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5511: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5512: 	}
1.157     albertel 5513:     } elsif ($field eq 'answer') {
1.497     foxr     5514: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5515: 	my $off=$scantron_config->{'Qoff'};
                   5516: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5517: 	my $answer=${off}x$length;
                   5518: 	if ($args->{'response'} eq 'none') {
                   5519: 	    &scan_data($scan_data,
1.503     raeburn  5520: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5521: 	} else {
                   5522: 	    if ($on eq 'letter') {
                   5523: 		my @alphabet=('A'..'Z');
                   5524: 		$answer=$alphabet[$args->{'response'}];
                   5525: 	    } elsif ($on eq 'number') {
                   5526: 		$answer=$args->{'response'}+1;
                   5527: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5528: 	    } else {
1.497     foxr     5529: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5530: 	    }
1.497     foxr     5531: 	    &scan_data($scan_data,
1.503     raeburn  5532: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5533: 	}
1.497     foxr     5534: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5535: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5536:     }
                   5537:     return $line;
                   5538: }
1.423     albertel 5539: 
                   5540: =pod
                   5541: 
                   5542: =item scan_data
                   5543: 
                   5544:     Edit or look up  an item in the scan_data hash.
                   5545: 
                   5546:   Arguments:
                   5547:     $scan_data  - The hash (see scantron_getfile)
                   5548:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5549:                   scantronfilename_key).
1.423     albertel 5550:     $data        - New value of the hash entry.
                   5551:     $delete      - If true, the entry is removed from the hash.
                   5552: 
                   5553:   Returns:
                   5554:     The new value of the hash table field (undefined if deleted).
                   5555: 
                   5556: =cut
                   5557: 
                   5558: 
1.157     albertel 5559: sub scan_data {
                   5560:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5561:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5562:     if (defined($value)) {
                   5563: 	$scan_data->{$filename.'_'.$key} = $value;
                   5564:     }
                   5565:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5566:     return $scan_data->{$filename.'_'.$key};
                   5567: }
1.423     albertel 5568: 
1.495     albertel 5569: # ----- These first few routines are general use routines.----
                   5570: 
                   5571: # Return the number of occurences of a pattern in a string.
                   5572: 
                   5573: sub occurence_count {
                   5574:     my ($string, $pattern) = @_;
                   5575: 
                   5576:     my @matches = ($string =~ /$pattern/g);
                   5577: 
                   5578:     return scalar(@matches);
                   5579: }
                   5580: 
                   5581: 
                   5582: # Take a string known to have digits and convert all the
                   5583: # digits into letters in the range J,A..I.
                   5584: 
                   5585: sub digits_to_letters {
                   5586:     my ($input) = @_;
                   5587: 
                   5588:     my @alphabet = ('J', 'A'..'I');
                   5589: 
                   5590:     my @input    = split(//, $input);
                   5591:     my $output ='';
                   5592:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5593: 	if ($input[$i] =~ /\d/) {
                   5594: 	    $output .= $alphabet[$input[$i]];
                   5595: 	} else {
                   5596: 	    $output .= $input[$i];
                   5597: 	}
                   5598:     }
                   5599:     return $output;
                   5600: }
                   5601: 
1.423     albertel 5602: =pod 
                   5603: 
                   5604: =item scantron_parse_scanline
                   5605: 
                   5606:   Decodes a scanline from the selected scantron file
                   5607: 
                   5608:  Arguments:
                   5609:     line             - The text of the scantron file line to process
                   5610:     whichline        - Line number
                   5611:     scantron_config  - Hash describing the format of the scantron lines.
                   5612:     scan_data        - Hash of extra information about the scanline
                   5613:                        (see scantron_getfile for more information)
                   5614:     just_header      - True if should not process question answers but only
                   5615:                        the stuff to the left of the answers.
                   5616:  Returns:
                   5617:    Hash containing the result of parsing the scanline
                   5618: 
                   5619:    Keys are all proceeded by the string 'scantron.'
                   5620: 
                   5621:        CODE    - the CODE in use for this scanline
                   5622:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5623:                  by the operator
                   5624:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5625:                             CODEs were selected, but the usage has been
                   5626:                             forced by the operator
                   5627:        ID  - student ID
                   5628:        PaperID - if used, the ID number printed on the sheet when the 
                   5629:                  paper was scanned
                   5630:        FirstName - first name from the sheet
                   5631:        LastName  - last name from the sheet
                   5632: 
                   5633:      if just_header was not true these key may also exist
                   5634: 
1.447     foxr     5635:        missingerror - a list of bubble ranges that are considered to be answers
                   5636:                       to a single question that don't have any bubbles filled in.
                   5637:                       Of the form questionnumber:firstbubblenumber:count.
                   5638:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5639:                       to a single question that have more than one bubble filled in.
                   5640:                       Of the form questionnumber::firstbubblenumber:count
                   5641:    
                   5642:                 In the above, count is the number of bubble responses in the
                   5643:                 input line needed to represent the possible answers to the question.
                   5644:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5645:                 per line would have count = 2.
                   5646: 
1.423     albertel 5647:        maxquest     - the number of the last bubble line that was parsed
                   5648: 
                   5649:        (<number> starts at 1)
                   5650:        <number>.answer - zero or more letters representing the selected
                   5651:                          letters from the scanline for the bubble line 
                   5652:                          <number>.
                   5653:                          if blank there was either no bubble or there where
                   5654:                          multiple bubbles, (consult the keys missingerror and
                   5655:                          doubleerror if this is an error condition)
                   5656: 
                   5657: =cut
                   5658: 
1.82      albertel 5659: sub scantron_parse_scanline {
1.423     albertel 5660:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5661: 
1.82      albertel 5662:     my %record;
1.422     foxr     5663:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5664:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5665:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5666: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5667: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5668: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5669: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5670: 	    $record{'scantron.CODE'}=substr($data,
                   5671: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5672: 					    $$scantron_config{'CODElength'});
1.191     albertel 5673: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5674: 		$record{'scantron.useCODE'}=1;
                   5675: 	    }
1.192     albertel 5676: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5677: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5678: 	    }
1.82      albertel 5679: 	} else {
                   5680: 	    #FIXME interpret first N questions
                   5681: 	}
                   5682:     }
1.83      albertel 5683:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5684: 				  $$scantron_config{'IDlength'});
1.157     albertel 5685:     $record{'scantron.PaperID'}=
                   5686: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5687: 	       $$scantron_config{'PaperIDlength'});
                   5688:     $record{'scantron.FirstName'}=
                   5689: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5690: 	       $$scantron_config{'FirstNamelength'});
                   5691:     $record{'scantron.LastName'}=
                   5692: 	substr($data,$$scantron_config{'LastName'}-1,
                   5693: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5694:     if ($just_header) { return \%record; }
1.194     albertel 5695: 
1.82      albertel 5696:     my @alphabet=('A'..'Z');
                   5697:     my $questnum=0;
1.447     foxr     5698:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5699: 
1.470     foxr     5700:     chomp($questions);		# Get rid of any trailing \n.
                   5701:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5702:     while (length($questions)) {
1.447     foxr     5703: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5704:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5705:                              || 1;
                   5706:         $questnum++;
                   5707:         my $quest_id = $questnum;
                   5708:         my $currentquest = substr($questions,0,$answer_length);
                   5709:         $questions       = substr($questions,$answer_length);
                   5710:         if (length($currentquest) < $answer_length) { next; }
                   5711: 
                   5712:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5713:             my $subquestnum = 1;
                   5714:             my $subquestions = $currentquest;
                   5715:             my @subanswers_needed = 
                   5716:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5717:             foreach my $subans (@subanswers_needed) {
                   5718:                 my $subans_length =
                   5719:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5720:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5721:                 $subquestions   = substr($subquestions,$subans_length);
                   5722:                 $quest_id = "$questnum.$subquestnum";
                   5723:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5724:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5725:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5726:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5727:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5728:                 } else {
                   5729:                     $ansnum = &scantron_validator_positional($ansnum,
                   5730:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5731:                 }
                   5732:                 $subquestnum ++;
                   5733:             }
                   5734:         } else {
                   5735:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5736:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5737:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5738:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5739:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5740:             } else {
                   5741:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5742:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5743:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5744:             }
                   5745:         }
                   5746:     }
                   5747:     $record{'scantron.maxquest'}=$questnum;
                   5748:     return \%record;
                   5749: }
1.447     foxr     5750: 
1.503     raeburn  5751: sub scantron_validator_lettnum {
                   5752:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5753:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5754: 
                   5755:     # Qon 'letter' implies for each slot in currquest we have:
                   5756:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5757:     #    about anything else (esp. a value of Qoff) for missing
                   5758:     #    bubbles.
                   5759:     #
                   5760:     # Qon 'number' implies each slot gives a digit that indexes the
                   5761:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5762:     #    and * or ? for double bubbles on a single line.
                   5763:     #
1.447     foxr     5764: 
1.503     raeburn  5765:     my $matchon;
                   5766:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5767:         $matchon = '[A-Z]';
                   5768:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5769:         $matchon = '\d';
                   5770:     }
                   5771:     my $occurrences = 0;
                   5772:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5773:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5774:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5775:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5776:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5777:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5778:         my @singlelines = split('',$currquest);
                   5779:         foreach my $entry (@singlelines) {
                   5780:             $occurrences = &occurence_count($entry,$matchon);
                   5781:             if ($occurrences > 1) {
                   5782:                 last;
                   5783:             }
                   5784:         } 
                   5785:     } else {
                   5786:         $occurrences = &occurence_count($currquest,$matchon); 
                   5787:     }
                   5788:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5789:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5790:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5791:             my $bubble = substr($currquest,$ans,1);
                   5792:             if ($bubble =~ /$matchon/ ) {
                   5793:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5794:                     if ($bubble == 0) {
                   5795:                         $bubble = 10; 
                   5796:                     }
                   5797:                     $record->{"scantron.$ansnum.answer"} = 
                   5798:                         $alphabet->[$bubble-1];
                   5799:                 } else {
                   5800:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5801:                 }
                   5802:             } else {
                   5803:                 $record->{"scantron.$ansnum.answer"}='';
                   5804:             }
                   5805:             $ansnum++;
                   5806:         }
                   5807:     } elsif (!defined($currquest)
                   5808:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5809:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5810:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5811:             $record->{"scantron.$ansnum.answer"}='';
                   5812:             $ansnum++;
                   5813:         }
                   5814:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5815:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5816:         }
                   5817:     } else {
                   5818:         if ($$scantron_config{'Qon'} eq 'number') {
                   5819:             $currquest = &digits_to_letters($currquest);            
                   5820:         }
                   5821:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5822:             my $bubble = substr($currquest,$ans,1);
                   5823:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5824:             $ansnum++;
                   5825:         }
                   5826:     }
                   5827:     return $ansnum;
                   5828: }
1.447     foxr     5829: 
1.503     raeburn  5830: sub scantron_validator_positional {
                   5831:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5832:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5833: 
1.503     raeburn  5834:     # Otherwise there's a positional notation;
                   5835:     # each bubble line requires Qlength items, and there are filled in
                   5836:     # bubbles for each case where there 'Qon' characters.
                   5837:     #
1.447     foxr     5838: 
1.503     raeburn  5839:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5840: 
1.503     raeburn  5841:     # If the split only gives us one element.. the full length of the
                   5842:     # answer string, no bubbles are filled in:
1.447     foxr     5843: 
1.507     raeburn  5844:     if ($answers_needed eq '') {
                   5845:         return;
                   5846:     }
                   5847: 
1.503     raeburn  5848:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5849:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5850:             $record->{"scantron.$ansnum.answer"}='';
                   5851:             $ansnum++;
                   5852:         }
                   5853:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5854:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5855:         }
                   5856:     } elsif (scalar(@array) == 2) {
                   5857:         my $location = length($array[0]);
                   5858:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5859:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5860:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5861:             if ($ans eq $line_num) {
                   5862:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5863:             } else {
                   5864:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5865:             }
                   5866:             $ansnum++;
                   5867:          }
                   5868:     } else {
                   5869:         #  If there's more than one instance of a bubble character
                   5870:         #  That's a double bubble; with positional notation we can
                   5871:         #  record all the bubbles filled in as well as the
                   5872:         #  fact this response consists of multiple bubbles.
                   5873:         #
                   5874:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5875:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5876:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5877:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5878:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5879:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5880:             my $doubleerror = 0;
                   5881:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5882:                    (!$doubleerror)) {
                   5883:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5884:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5885:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5886:                if (length(@currarray) > 2) {
                   5887:                    $doubleerror = 1;
                   5888:                } 
                   5889:             }
                   5890:             if ($doubleerror) {
                   5891:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5892:             }
                   5893:         } else {
                   5894:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5895:         }
                   5896:         my $item = $ansnum;
                   5897:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5898:             $record->{"scantron.$item.answer"} = '';
                   5899:             $item ++;
                   5900:         }
1.447     foxr     5901: 
1.503     raeburn  5902:         my @ans=@array;
                   5903:         my $i=0;
                   5904:         my $increment = 0;
                   5905:         while ($#ans) {
                   5906:             $i+=length($ans[0]) + $increment;
                   5907:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5908:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5909:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5910:             shift(@ans);
                   5911:             $increment = 1;
                   5912:         }
                   5913:         $ansnum += $answers_needed;
1.82      albertel 5914:     }
1.503     raeburn  5915:     return $ansnum;
1.82      albertel 5916: }
                   5917: 
1.423     albertel 5918: =pod
                   5919: 
                   5920: =item scantron_add_delay
                   5921: 
                   5922:    Adds an error message that occurred during the grading phase to a
                   5923:    queue of messages to be shown after grading pass is complete
                   5924: 
                   5925:  Arguments:
1.424     albertel 5926:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5927:    $scanline    - the scanline that caused the error
                   5928:    $errormesage - the error message
                   5929:    $errorcode   - a numeric code for the error
                   5930: 
                   5931:  Side Effects:
1.424     albertel 5932:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5933: 
                   5934: =cut
                   5935: 
1.82      albertel 5936: sub scantron_add_delay {
1.140     albertel 5937:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5938:     push(@$delayqueue,
                   5939: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5940: 	  'ecode' => $errorcode }
                   5941: 	 );
1.82      albertel 5942: }
                   5943: 
1.423     albertel 5944: =pod
                   5945: 
                   5946: =item scantron_find_student
                   5947: 
1.424     albertel 5948:    Finds the username for the current scanline
                   5949: 
                   5950:   Arguments:
                   5951:    $scantron_record - hash result from scantron_parse_scanline
                   5952:    $scan_data       - hash of correction information 
                   5953:                       (see &scantron_getfile() form more information)
                   5954:    $idmap           - hash from &username_to_idmap()
                   5955:    $line            - number of current scanline
                   5956:  
                   5957:   Returns:
                   5958:    Either 'username:domain' or undef if unknown
                   5959: 
1.423     albertel 5960: =cut
                   5961: 
1.82      albertel 5962: sub scantron_find_student {
1.157     albertel 5963:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5964:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5965:     if ($scanID =~ /^\s*$/) {
                   5966:  	return &scan_data($scan_data,"$line.user");
                   5967:     }
1.83      albertel 5968:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5969:  	if (lc($id) eq lc($scanID)) {
                   5970:  	    return $$idmap{$id};
                   5971:  	}
1.83      albertel 5972:     }
                   5973:     return undef;
                   5974: }
                   5975: 
1.423     albertel 5976: =pod
                   5977: 
                   5978: =item scantron_filter
                   5979: 
1.424     albertel 5980:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5981:    hidden resources was selected
                   5982: 
1.423     albertel 5983: =cut
                   5984: 
1.83      albertel 5985: sub scantron_filter {
                   5986:     my ($curres)=@_;
1.331     albertel 5987: 
                   5988:     if (ref($curres) && $curres->is_problem()) {
                   5989: 	# if the user has asked to not have either hidden
                   5990: 	# or 'randomout' controlled resources to be graded
                   5991: 	# don't include them
                   5992: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5993: 	    && $curres->randomout) {
                   5994: 	    return 0;
                   5995: 	}
1.83      albertel 5996: 	return 1;
                   5997:     }
                   5998:     return 0;
1.82      albertel 5999: }
                   6000: 
1.423     albertel 6001: =pod
                   6002: 
                   6003: =item scantron_process_corrections
                   6004: 
1.424     albertel 6005:    Gets correction information out of submitted form data and corrects
                   6006:    the scanline
                   6007: 
1.423     albertel 6008: =cut
                   6009: 
1.157     albertel 6010: sub scantron_process_corrections {
                   6011:     my ($r) = @_;
1.257     albertel 6012:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6013:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6014:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6015:     my $which=$env{'form.scantron_line'};
1.200     albertel 6016:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6017:     my ($skip,$err,$errmsg);
1.257     albertel 6018:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6019: 	$skip=1;
1.257     albertel 6020:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6021: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6022: 	    $env{'form.scantron_domain'};
1.157     albertel 6023: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6024: 	($line,$err,$errmsg)=
                   6025: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6026: 				     'ID',{'newid'=>$newid,
1.257     albertel 6027: 				    'username'=>$env{'form.scantron_username'},
                   6028: 				    'domain'=>$env{'form.scantron_domain'}});
                   6029:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6030: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6031: 	my $newCODE;
1.192     albertel 6032: 	my %args;
1.190     albertel 6033: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6034: 	    $newCODE='use_unfound';
1.190     albertel 6035: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6036: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6037: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6038: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6039: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6040: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6041: 	}
1.257     albertel 6042: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6043: 	    $args{'CODE_ignore_dup'}=1;
                   6044: 	}
                   6045: 	$args{'CODE'}=$newCODE;
1.186     albertel 6046: 	($line,$err,$errmsg)=
                   6047: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6048: 				     'CODE',\%args);
1.257     albertel 6049:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6050: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6051: 	    ($line,$err,$errmsg)=
                   6052: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6053: 					 $which,'answer',
                   6054: 					 { 'question'=>$question,
1.503     raeburn  6055: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6056:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6057: 	    if ($err) { last; }
                   6058: 	}
                   6059:     }
                   6060:     if ($err) {
1.398     albertel 6061: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6062:     } else {
1.200     albertel 6063: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6064: 	&scantron_putfile($scanlines,$scan_data);
                   6065:     }
                   6066: }
                   6067: 
1.423     albertel 6068: =pod
                   6069: 
                   6070: =item reset_skipping_status
                   6071: 
1.424     albertel 6072:    Forgets the current set of remember skipped scanlines (and thus
                   6073:    reverts back to considering all lines in the
                   6074:    scantron_skipped_<filename> file)
                   6075: 
1.423     albertel 6076: =cut
                   6077: 
1.200     albertel 6078: sub reset_skipping_status {
                   6079:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6080:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6081:     &scantron_putfile(undef,$scan_data);
                   6082: }
                   6083: 
1.423     albertel 6084: =pod
                   6085: 
                   6086: =item start_skipping
                   6087: 
1.424     albertel 6088:    Marks a scanline to be skipped. 
                   6089: 
1.423     albertel 6090: =cut
                   6091: 
1.376     albertel 6092: sub start_skipping {
1.200     albertel 6093:     my ($scan_data,$i)=@_;
                   6094:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6095:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6096: 	$remembered{$i}=2;
                   6097:     } else {
                   6098: 	$remembered{$i}=1;
                   6099:     }
1.200     albertel 6100:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6101: }
                   6102: 
1.423     albertel 6103: =pod
                   6104: 
                   6105: =item should_be_skipped
                   6106: 
1.424     albertel 6107:    Checks whether a scanline should be skipped.
                   6108: 
1.423     albertel 6109: =cut
                   6110: 
1.200     albertel 6111: sub should_be_skipped {
1.376     albertel 6112:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6113:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6114: 	# not redoing old skips
1.376     albertel 6115: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6116: 	return 0;
                   6117:     }
                   6118:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6119: 
                   6120:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6121: 	return 0;
                   6122:     }
1.200     albertel 6123:     return 1;
                   6124: }
                   6125: 
1.423     albertel 6126: =pod
                   6127: 
                   6128: =item remember_current_skipped
                   6129: 
1.424     albertel 6130:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6131:    file and remembers them into scan_data for later use.
                   6132: 
1.423     albertel 6133: =cut
                   6134: 
1.200     albertel 6135: sub remember_current_skipped {
                   6136:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6137:     my %to_remember;
                   6138:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6139: 	if ($scanlines->{'skipped'}[$i]) {
                   6140: 	    $to_remember{$i}=1;
                   6141: 	}
                   6142:     }
1.376     albertel 6143: 
1.200     albertel 6144:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6145:     &scantron_putfile(undef,$scan_data);
                   6146: }
                   6147: 
1.423     albertel 6148: =pod
                   6149: 
                   6150: =item check_for_error
                   6151: 
1.424     albertel 6152:     Checks if there was an error when attempting to remove a specific
                   6153:     scantron_.. bubble sheet data file. Prints out an error if
                   6154:     something went wrong.
                   6155: 
1.423     albertel 6156: =cut
                   6157: 
1.200     albertel 6158: sub check_for_error {
                   6159:     my ($r,$result)=@_;
                   6160:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6161: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6162:     }
                   6163: }
1.157     albertel 6164: 
1.423     albertel 6165: =pod
                   6166: 
                   6167: =item scantron_warning_screen
                   6168: 
1.424     albertel 6169:    Interstitial screen to make sure the operator has selected the
                   6170:    correct options before we start the validation phase.
                   6171: 
1.423     albertel 6172: =cut
                   6173: 
1.203     albertel 6174: sub scantron_warning_screen {
                   6175:     my ($button_text)=@_;
1.257     albertel 6176:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6177:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6178:     my $CODElist;
1.284     albertel 6179:     if ($scantron_config{'CODElocation'} &&
                   6180: 	$scantron_config{'CODEstart'} &&
                   6181: 	$scantron_config{'CODElength'}) {
                   6182: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6183: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6184: 	$CODElist=
1.492     albertel 6185: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6186: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6187:     }
1.492     albertel 6188:     return ('
1.203     albertel 6189: <p>
1.492     albertel 6190: <span class="LC_warning">
                   6191: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6192: </p>
                   6193: <table>
1.492     albertel 6194: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6195: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6196: '.$CODElist.'
1.203     albertel 6197: </table>
                   6198: <br />
1.492     albertel 6199: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6200: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6201: 
                   6202: <br />
1.492     albertel 6203: ');
1.203     albertel 6204: }
                   6205: 
1.423     albertel 6206: =pod
                   6207: 
                   6208: =item scantron_do_warning
                   6209: 
1.424     albertel 6210:    Check if the operator has picked something for all required
                   6211:    fields. Error out if something is missing.
                   6212: 
1.423     albertel 6213: =cut
                   6214: 
1.203     albertel 6215: sub scantron_do_warning {
                   6216:     my ($r)=@_;
1.324     albertel 6217:     my ($symb)=&get_symb($r);
1.203     albertel 6218:     if (!$symb) {return '';}
1.324     albertel 6219:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6220:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6221:     if ( $env{'form.selectpage'} eq '' ||
                   6222: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6223: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6224: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6225: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6226: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6227: 	} 
1.257     albertel 6228: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6229: 	    $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 6230: 	} 
1.257     albertel 6231: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6232: 	    $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 6233: 	} 
                   6234:     } else {
1.265     www      6235: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6236: 	$r->print('
                   6237: '.$warning.'
                   6238: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6239: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6240: ');
1.237     albertel 6241:     }
1.352     albertel 6242:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6243:     return '';
                   6244: }
                   6245: 
1.423     albertel 6246: =pod
                   6247: 
                   6248: =item scantron_form_start
                   6249: 
1.424     albertel 6250:     html hidden input for remembering all selected grading options
                   6251: 
1.423     albertel 6252: =cut
                   6253: 
1.203     albertel 6254: sub scantron_form_start {
                   6255:     my ($max_bubble)=@_;
                   6256:     my $result= <<SCANTRONFORM;
                   6257: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6258:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6259:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6260:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6261:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6262:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6263:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6264:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6265:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6266:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6267: SCANTRONFORM
1.447     foxr     6268: 
                   6269:   my $line = 0;
                   6270:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6271:        my $chunk =
                   6272: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6273:        $chunk .=
                   6274: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6275:        $chunk .= 
                   6276:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6277:        $chunk .=
                   6278:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6279:        $result .= $chunk;
                   6280:        $line++;
                   6281:    }
1.203     albertel 6282:     return $result;
                   6283: }
                   6284: 
1.423     albertel 6285: =pod
                   6286: 
                   6287: =item scantron_validate_file
                   6288: 
1.424     albertel 6289:     Dispatch routine for doing validation of a bubble sheet data file.
                   6290: 
                   6291:     Also processes any necessary information resets that need to
                   6292:     occur before validation begins (ignore previous corrections,
                   6293:     restarting the skipped records processing)
                   6294: 
1.423     albertel 6295: =cut
                   6296: 
1.157     albertel 6297: sub scantron_validate_file {
                   6298:     my ($r) = @_;
1.324     albertel 6299:     my ($symb)=&get_symb($r);
1.157     albertel 6300:     if (!$symb) {return '';}
1.324     albertel 6301:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6302:     
                   6303:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6304:     # them when doing the corrections reset
1.257     albertel 6305:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6306: 	&reset_skipping_status();
                   6307:     }
1.257     albertel 6308:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6309: 	&remember_current_skipped();
1.257     albertel 6310: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6311:     }
                   6312: 
1.257     albertel 6313:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6314: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6315: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6316: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6317: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6318:     }
1.200     albertel 6319: 
1.257     albertel 6320:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6321: 	&scantron_process_corrections($r);
                   6322:     }
1.503     raeburn  6323:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6324:     #get the student pick code ready
                   6325:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 6326:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 6327:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6328:     $r->print($result);
                   6329:     
1.334     albertel 6330:     my @validate_phases=( 'sequence',
                   6331: 			  'ID',
1.157     albertel 6332: 			  'CODE',
                   6333: 			  'doublebubble',
                   6334: 			  'missingbubbles');
1.257     albertel 6335:     if (!$env{'form.validatepass'}) {
                   6336: 	$env{'form.validatepass'} = 0;
1.157     albertel 6337:     }
1.257     albertel 6338:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6339: 
1.448     foxr     6340: 
1.157     albertel 6341:     my $stop=0;
                   6342:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6343: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6344: 	$r->rflush();
                   6345: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6346: 	{
                   6347: 	    no strict 'refs';
                   6348: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6349: 	}
                   6350:     }
                   6351:     if (!$stop) {
1.203     albertel 6352: 	my $warning=&scantron_warning_screen('Start Grading');
1.512     www      6353: 	$r->print(&mt('Validation process complete.').'<br />
1.492     albertel 6354: '.$warning.'
                   6355: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
1.203     albertel 6356: <input type="hidden" name="command" value="scantron_process" />
1.492     albertel 6357: ');
1.203     albertel 6358: 
1.157     albertel 6359:     } else {
                   6360: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6361: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6362:     }
                   6363:     if ($stop) {
1.334     albertel 6364: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.492     albertel 6365: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
                   6366: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6367: 
1.492     albertel 6368: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6369: 	} else {
1.503     raeburn  6370:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
                   6371: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
                   6372:             } else {
                   6373:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
                   6374:             }
1.492     albertel 6375: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6376: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6377: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6378: 	}
1.157     albertel 6379:     }
1.352     albertel 6380:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6381:     return '';
                   6382: }
                   6383: 
1.423     albertel 6384: 
                   6385: =pod
                   6386: 
                   6387: =item scantron_remove_file
                   6388: 
1.424     albertel 6389:    Removes the requested bubble sheet data file, makes sure that
                   6390:    scantron_original_<filename> is never removed
                   6391: 
                   6392: 
1.423     albertel 6393: =cut
                   6394: 
1.200     albertel 6395: sub scantron_remove_file {
1.192     albertel 6396:     my ($which)=@_;
1.257     albertel 6397:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6398:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6399:     my $file='scantron_';
1.200     albertel 6400:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6401: 	$file.=$which.'_';
1.192     albertel 6402:     } else {
                   6403: 	return 'refused';
                   6404:     }
1.257     albertel 6405:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6406:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6407: }
                   6408: 
1.423     albertel 6409: 
                   6410: =pod
                   6411: 
                   6412: =item scantron_remove_scan_data
                   6413: 
1.424     albertel 6414:    Removes all scan_data correction for the requested bubble sheet
                   6415:    data file.  (In the case that both the are doing skipped records we need
                   6416:    to remember the old skipped lines for the time being so that element
                   6417:    persists for a while.)
                   6418: 
1.423     albertel 6419: =cut
                   6420: 
1.200     albertel 6421: sub scantron_remove_scan_data {
1.257     albertel 6422:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6423:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6424:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6425:     my @todelete;
1.257     albertel 6426:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6427:     foreach my $key (@keys) {
                   6428: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6429: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6430: 		$key=~/remember_skipping/) {
                   6431: 		next;
                   6432: 	    }
1.192     albertel 6433: 	    push(@todelete,$key);
                   6434: 	}
                   6435:     }
1.200     albertel 6436:     my $result;
1.192     albertel 6437:     if (@todelete) {
1.491     albertel 6438: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6439: 				       \@todelete,$cdom,$cname);
                   6440:     } else {
                   6441: 	$result = 'ok';
1.192     albertel 6442:     }
                   6443:     return $result;
                   6444: }
                   6445: 
1.423     albertel 6446: 
                   6447: =pod
                   6448: 
                   6449: =item scantron_getfile
                   6450: 
1.424     albertel 6451:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6452:     the scan_data hash
                   6453:   
                   6454:   Arguments:
                   6455:     None
                   6456: 
                   6457:   Returns:
                   6458:     2 hash references
                   6459: 
                   6460:      - first one has 
                   6461:          orig      -
                   6462:          corrected -
                   6463:          skipped   -  each of which points to an array ref of the specified
                   6464:                       file broken up into individual lines
                   6465:          count     - number of scanlines
                   6466:  
                   6467:      - second is the scan_data hash possible keys are
1.425     albertel 6468:        ($number refers to scanline numbered $number and thus the key affects
                   6469:         only that scanline
                   6470:         $bubline refers to the specific bubble line element and the aspects
                   6471:         refers to that specific bubble line element)
                   6472: 
                   6473:        $number.user - username:domain to use
                   6474:        $number.CODE_ignore_dup 
                   6475:                     - ignore the duplicate CODE error 
                   6476:        $number.useCODE
                   6477:                     - use the CODE in the scanline as is
                   6478:        $number.no_bubble.$bubline
                   6479:                     - it is valid that there is no bubbled in bubble
                   6480:                       at $number $bubline
                   6481:        remember_skipping
                   6482:                     - a frozen hash containing keys of $number and values
                   6483:                       of either 
                   6484:                         1 - we are on a 'do skipped records pass' and plan
                   6485:                             on processing this line
                   6486:                         2 - we are on a 'do skipped records pass' and this
                   6487:                             scanline has been marked to skip yet again
1.424     albertel 6488: 
1.423     albertel 6489: =cut
                   6490: 
1.157     albertel 6491: sub scantron_getfile {
1.200     albertel 6492:     #FIXME really would prefer a scantron directory
1.257     albertel 6493:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6494:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6495:     my $lines;
                   6496:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6497: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6498:     my %scanlines;
                   6499:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6500:     my $temp=$scanlines{'orig'};
                   6501:     $scanlines{'count'}=$#$temp;
                   6502: 
                   6503:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6504: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6505:     if ($lines eq '-1') {
                   6506: 	$scanlines{'corrected'}=[];
                   6507:     } else {
                   6508: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6509:     }
                   6510:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6511: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6512:     if ($lines eq '-1') {
                   6513: 	$scanlines{'skipped'}=[];
                   6514:     } else {
                   6515: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6516:     }
1.175     albertel 6517:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6518:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6519:     my %scan_data = @tmp;
                   6520:     return (\%scanlines,\%scan_data);
                   6521: }
                   6522: 
1.423     albertel 6523: =pod
                   6524: 
                   6525: =item lonnet_putfile
                   6526: 
1.424     albertel 6527:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6528: 
                   6529:  Arguments:
                   6530:    $contents - data to store
                   6531:    $filename - filename to store $contents into
                   6532: 
                   6533:  Returns:
                   6534:    result value from &Apache::lonnet::finishuserfileupload
                   6535: 
1.423     albertel 6536: =cut
                   6537: 
1.157     albertel 6538: sub lonnet_putfile {
                   6539:     my ($contents,$filename)=@_;
1.257     albertel 6540:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6541:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6542:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6543:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6544: 
                   6545: }
                   6546: 
1.423     albertel 6547: =pod
                   6548: 
                   6549: =item scantron_putfile
                   6550: 
1.424     albertel 6551:     Stores the current version of the bubble sheet data files, and the
                   6552:     scan_data hash. (Does not modify the original version only the
                   6553:     corrected and skipped versions.
                   6554: 
                   6555:  Arguments:
                   6556:     $scanlines - hash ref that looks like the first return value from
                   6557:                  &scantron_getfile()
                   6558:     $scan_data - hash ref that looks like the second return value from
                   6559:                  &scantron_getfile()
                   6560: 
1.423     albertel 6561: =cut
                   6562: 
1.157     albertel 6563: sub scantron_putfile {
                   6564:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6565:     #FIXME really would prefer a scantron directory
1.257     albertel 6566:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6567:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6568:     if ($scanlines) {
                   6569: 	my $prefix='scantron_';
1.157     albertel 6570: # no need to update orig, shouldn't change
                   6571: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6572: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6573: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6574: 			$prefix.'corrected_'.
1.257     albertel 6575: 			$env{'form.scantron_selectfile'});
1.200     albertel 6576: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6577: 			$prefix.'skipped_'.
1.257     albertel 6578: 			$env{'form.scantron_selectfile'});
1.200     albertel 6579:     }
1.175     albertel 6580:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6581: }
                   6582: 
1.423     albertel 6583: =pod
                   6584: 
                   6585: =item scantron_get_line
                   6586: 
1.424     albertel 6587:    Returns the correct version of the scanline
                   6588: 
                   6589:  Arguments:
                   6590:     $scanlines - hash ref that looks like the first return value from
                   6591:                  &scantron_getfile()
                   6592:     $scan_data - hash ref that looks like the second return value from
                   6593:                  &scantron_getfile()
                   6594:     $i         - number of the requested line (starts at 0)
                   6595: 
                   6596:  Returns:
                   6597:    A scanline, (either the original or the corrected one if it
                   6598:    exists), or undef if the requested scanline should be
                   6599:    skipped. (Either because it's an skipped scanline, or it's an
                   6600:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6601:    pass.
                   6602: 
1.423     albertel 6603: =cut
                   6604: 
1.157     albertel 6605: sub scantron_get_line {
1.200     albertel 6606:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6607:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6608:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6609:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6610:     return $scanlines->{'orig'}[$i]; 
                   6611: }
                   6612: 
1.423     albertel 6613: =pod
                   6614: 
                   6615: =item scantron_todo_count
                   6616: 
1.424     albertel 6617:     Counts the number of scanlines that need processing.
                   6618: 
                   6619:  Arguments:
                   6620:     $scanlines - hash ref that looks like the first return value from
                   6621:                  &scantron_getfile()
                   6622:     $scan_data - hash ref that looks like the second return value from
                   6623:                  &scantron_getfile()
                   6624: 
                   6625:  Returns:
                   6626:     $count - number of scanlines to process
                   6627: 
1.423     albertel 6628: =cut
                   6629: 
1.200     albertel 6630: sub get_todo_count {
                   6631:     my ($scanlines,$scan_data)=@_;
                   6632:     my $count=0;
                   6633:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6634: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6635: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6636: 	$count++;
                   6637:     }
                   6638:     return $count;
                   6639: }
                   6640: 
1.423     albertel 6641: =pod
                   6642: 
                   6643: =item scantron_put_line
                   6644: 
1.424     albertel 6645:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6646:     data file.
                   6647: 
                   6648:  Arguments:
                   6649:     $scanlines - hash ref that looks like the first return value from
                   6650:                  &scantron_getfile()
                   6651:     $scan_data - hash ref that looks like the second return value from
                   6652:                  &scantron_getfile()
                   6653:     $i         - line number to update
                   6654:     $newline   - contents of the updated scanline
                   6655:     $skip      - if true make the line for skipping and update the
                   6656:                  'skipped' file
                   6657: 
1.423     albertel 6658: =cut
                   6659: 
1.157     albertel 6660: sub scantron_put_line {
1.200     albertel 6661:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6662:     if ($skip) {
                   6663: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6664: 	&start_skipping($scan_data,$i);
1.157     albertel 6665: 	return;
                   6666:     }
                   6667:     $scanlines->{'corrected'}[$i]=$newline;
                   6668: }
                   6669: 
1.423     albertel 6670: =pod
                   6671: 
                   6672: =item scantron_clear_skip
                   6673: 
1.424     albertel 6674:    Remove a line from the 'skipped' file
                   6675: 
                   6676:  Arguments:
                   6677:     $scanlines - hash ref that looks like the first return value from
                   6678:                  &scantron_getfile()
                   6679:     $scan_data - hash ref that looks like the second return value from
                   6680:                  &scantron_getfile()
                   6681:     $i         - line number to update
                   6682: 
1.423     albertel 6683: =cut
                   6684: 
1.376     albertel 6685: sub scantron_clear_skip {
                   6686:     my ($scanlines,$scan_data,$i)=@_;
                   6687:     if (exists($scanlines->{'skipped'}[$i])) {
                   6688: 	undef($scanlines->{'skipped'}[$i]);
                   6689: 	return 1;
                   6690:     }
                   6691:     return 0;
                   6692: }
                   6693: 
1.423     albertel 6694: =pod
                   6695: 
                   6696: =item scantron_filter_not_exam
                   6697: 
1.424     albertel 6698:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6699:    filter out resources that are not marked as 'exam' mode
                   6700: 
1.423     albertel 6701: =cut
                   6702: 
1.334     albertel 6703: sub scantron_filter_not_exam {
                   6704:     my ($curres)=@_;
                   6705:     
                   6706:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6707: 	# if the user has asked to not have either hidden
                   6708: 	# or 'randomout' controlled resources to be graded
                   6709: 	# don't include them
                   6710: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6711: 	    && $curres->randomout) {
                   6712: 	    return 0;
                   6713: 	}
                   6714: 	return 1;
                   6715:     }
                   6716:     return 0;
                   6717: }
                   6718: 
1.423     albertel 6719: =pod
                   6720: 
                   6721: =item scantron_validate_sequence
                   6722: 
1.424     albertel 6723:     Validates the selected sequence, checking for resource that are
                   6724:     not set to exam mode.
                   6725: 
1.423     albertel 6726: =cut
                   6727: 
1.334     albertel 6728: sub scantron_validate_sequence {
                   6729:     my ($r,$currentphase) = @_;
                   6730: 
                   6731:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6732:     my (undef,undef,$sequence)=
                   6733: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6734: 
                   6735:     my $map=$navmap->getResourceByUrl($sequence);
                   6736: 
                   6737:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6738:                                     value="ignore" />');
                   6739:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6740: 	my @resources=
                   6741: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6742: 	if (@resources) {
1.357     banghart 6743: 	    $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 6744: 	    return (1,$currentphase);
                   6745: 	}
                   6746:     }
                   6747: 
                   6748:     return (0,$currentphase+1);
                   6749: }
                   6750: 
1.423     albertel 6751: 
                   6752: 
1.157     albertel 6753: sub scantron_validate_ID {
                   6754:     my ($r,$currentphase) = @_;
                   6755:     
                   6756:     #get student info
                   6757:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6758:     my %idmap=&username_to_idmap($classlist);
                   6759: 
                   6760:     #get scantron line setup
1.257     albertel 6761:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6762:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6763:     
                   6764:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6765: 
                   6766:     my %found=('ids'=>{},'usernames'=>{});
                   6767:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6768: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6769: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6770: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6771: 						 $scan_data);
                   6772: 	my $id=$$scan_record{'scantron.ID'};
                   6773: 	my $found;
                   6774: 	foreach my $checkid (keys(%idmap)) {
                   6775: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6776: 	}
                   6777: 	if ($found) {
                   6778: 	    my $username=$idmap{$found};
                   6779: 	    if ($found{'ids'}{$found}) {
                   6780: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6781: 					 $line,'duplicateID',$found);
1.194     albertel 6782: 		return(1,$currentphase);
1.157     albertel 6783: 	    } elsif ($found{'usernames'}{$username}) {
                   6784: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6785: 					 $line,'duplicateID',$username);
1.194     albertel 6786: 		return(1,$currentphase);
1.157     albertel 6787: 	    }
1.186     albertel 6788: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6789: 	    $found{'ids'}{$found}++;
                   6790: 	    $found{'usernames'}{$username}++;
                   6791: 	} else {
                   6792: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6793: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6794: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6795: 		    &scantron_get_correction($r,$i,$scan_record,
                   6796: 					     \%scantron_config,
                   6797: 					     $line,'duplicateID',$username);
1.194     albertel 6798: 		    return(1,$currentphase);
1.157     albertel 6799: 		} elsif (!defined($username)) {
                   6800: 		    &scantron_get_correction($r,$i,$scan_record,
                   6801: 					     \%scantron_config,
                   6802: 					     $line,'incorrectID');
1.194     albertel 6803: 		    return(1,$currentphase);
1.157     albertel 6804: 		}
                   6805: 		$found{'usernames'}{$username}++;
                   6806: 	    } else {
                   6807: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6808: 					 $line,'incorrectID');
1.194     albertel 6809: 		return(1,$currentphase);
1.157     albertel 6810: 	    }
                   6811: 	}
                   6812:     }
                   6813: 
                   6814:     return (0,$currentphase+1);
                   6815: }
                   6816: 
1.423     albertel 6817: 
1.157     albertel 6818: sub scantron_get_correction {
                   6819:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6820: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6821: #to show both the current line and the previous one and allow skipping
                   6822: #the previous one or the current one
                   6823: 
1.333     albertel 6824:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6825: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6826: 			    " for PaperID <tt>[_1]</tt>",
                   6827: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6828:     } else {
1.492     albertel 6829: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6830: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6831: 			    $i,$line)."</p> \n");
                   6832:     }
                   6833:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6834: 			  "The name on the paper is [_2],[_3]",
                   6835: 			  $$scan_record{'scantron.ID'},
                   6836: 			  $$scan_record{'scantron.LastName'},
                   6837: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6838: 
1.157     albertel 6839:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6840:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6841:                            # Array populated for doublebubble or
                   6842:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6843:                            # to validate radio button checking   
                   6844: 
1.157     albertel 6845:     if ($error =~ /ID$/) {
1.186     albertel 6846: 	if ($error eq 'incorrectID') {
1.492     albertel 6847: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6848: 		      "</p>\n");
1.157     albertel 6849: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6850: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6851: 	}
1.242     albertel 6852: 	$r->print($message);
1.492     albertel 6853: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6854: 	$r->print("\n<ul><li> ");
                   6855: 	#FIXME it would be nice if this sent back the user ID and
                   6856: 	#could do partial userID matches
                   6857: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6858: 				       'scantron_username','scantron_domain'));
                   6859: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6860: 	$r->print("\n@".
1.257     albertel 6861: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6862: 
                   6863: 	$r->print('</li>');
1.186     albertel 6864:     } elsif ($error =~ /CODE$/) {
                   6865: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6866: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6867: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6868: 	    $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 6869: 	}
1.492     albertel 6870: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6871: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6872: 	$r->print($message);
1.492     albertel 6873: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6874: 	$r->print("\n<br /> ");
1.194     albertel 6875: 	my $i=0;
1.273     albertel 6876: 	if ($error eq 'incorrectCODE' 
                   6877: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6878: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6879: 	    if ($closest > 0) {
                   6880: 		foreach my $testcode (@{$closest}) {
                   6881: 		    my $checked='';
1.401     albertel 6882: 		    if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6883: 		    $r->print("
                   6884:    <label>
                   6885:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
                   6886:        ".&mt("Use the similar CODE [_1] instead.",
                   6887: 	    "<b><tt>".$testcode."</tt></b>")."
                   6888:     </label>
                   6889:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6890: 		    $r->print("\n<br />");
                   6891: 		    $i++;
                   6892: 		}
1.194     albertel 6893: 	    }
                   6894: 	}
1.273     albertel 6895: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6896: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6897: 	    $r->print("
                   6898:     <label>
                   6899:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
                   6900:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6901: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6902:     </label>");
1.273     albertel 6903: 	    $r->print("\n<br />");
                   6904: 	}
1.194     albertel 6905: 
1.188     albertel 6906: 	$r->print(<<ENDSCRIPT);
                   6907: <script type="text/javascript">
                   6908: function change_radio(field) {
1.190     albertel 6909:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6910:     var i;
                   6911:     for (i=0;i<slct.length;i++) {
                   6912:         if (slct[i].value==field) { slct[i].checked=true; }
                   6913:     }
                   6914: }
                   6915: </script>
                   6916: ENDSCRIPT
1.187     albertel 6917: 	my $href="/adm/pickcode?".
1.359     www      6918: 	   "form=".&escape("scantronupload").
                   6919: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6920: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6921: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6922: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6923: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6924: 	    $r->print("
                   6925:     <label>
                   6926:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6927:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6928: 	     "<a target='_blank' href='$href'>","</a>")."
                   6929:     </label> 
                   6930:     ".&mt("Selected CODE is [_1]","<input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />"));
1.332     albertel 6931: 	    $r->print("\n<br />");
                   6932: 	}
1.492     albertel 6933: 	$r->print("
                   6934:     <label>
                   6935:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6936:        ".&mt("Use [_1] as the CODE.",
                   6937: 	     "</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 6938: 	$r->print("\n<br /><br />");
1.157     albertel 6939:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6940: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6941: 
                   6942: 	# The form field scantron_questions is acutally a list of line numbers.
                   6943: 	# represented by this form so:
                   6944: 
                   6945: 	my $line_list = &questions_to_line_list($arg);
                   6946: 
1.157     albertel 6947: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6948: 		  $line_list.'" />');
1.242     albertel 6949: 	$r->print($message);
1.492     albertel 6950: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6951: 	foreach my $question (@{$arg}) {
1.503     raeburn  6952: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6953:                                                    $scan_record, $error);
1.524     raeburn  6954:             push(@lines_to_correct,@linenums);
1.157     albertel 6955: 	}
1.503     raeburn  6956:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6957:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6958: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6959: 	$r->print($message);
1.492     albertel 6960: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6961: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6962: 
1.503     raeburn  6963: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6964: 	# a list of question numbers. Therefore:
                   6965: 	#
                   6966: 	
                   6967: 	my $line_list = &questions_to_line_list($arg);
                   6968: 
1.157     albertel 6969: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6970: 		  $line_list.'" />');
1.157     albertel 6971: 	foreach my $question (@{$arg}) {
1.503     raeburn  6972: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6973:                                                    $scan_record, $error);
1.524     raeburn  6974:             push(@lines_to_correct,@linenums);
1.157     albertel 6975: 	}
1.503     raeburn  6976:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6977:     } else {
                   6978: 	$r->print("\n<ul>");
                   6979:     }
                   6980:     $r->print("\n</li></ul>");
1.497     foxr     6981: }
                   6982: 
1.503     raeburn  6983: sub verify_bubbles_checked {
                   6984:     my (@ansnums) = @_;
                   6985:     my $ansnumstr = join('","',@ansnums);
                   6986:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6987:     my $output = (<<ENDSCRIPT);
                   6988: <script type="text/javascript">
                   6989: function verify_bubble_radio(form) {
                   6990:     var ansnumArray = new Array ("$ansnumstr");
                   6991:     var need_bubble_count = 0;
                   6992:     for (var i=0; i<ansnumArray.length; i++) {
                   6993:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6994:             var bubble_picked = 0; 
                   6995:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6996:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6997:                     bubble_picked = 1;
                   6998:                 }
                   6999:             }
                   7000:             if (bubble_picked == 0) {
                   7001:                 need_bubble_count ++;
                   7002:             }
                   7003:         }
                   7004:     }
                   7005:     if (need_bubble_count) {
                   7006:         alert("$warning");
                   7007:         return;
                   7008:     }
                   7009:     form.submit(); 
                   7010: }
                   7011: </script>
                   7012: ENDSCRIPT
                   7013:     return $output;
                   7014: }
                   7015: 
1.497     foxr     7016: =pod
                   7017: 
                   7018: =item  questions_to_line_list
1.157     albertel 7019: 
1.497     foxr     7020: Converts a list of questions into a string of comma separated
                   7021: line numbers in the answer sheet used by the questions.  This is
                   7022: used to fill in the scantron_questions form field.
                   7023: 
                   7024:   Arguments:
                   7025:      questions    - Reference to an array of questions.
                   7026: 
                   7027: =cut
                   7028: 
                   7029: 
                   7030: sub questions_to_line_list {
                   7031:     my ($questions) = @_;
                   7032:     my @lines;
                   7033: 
1.503     raeburn  7034:     foreach my $item (@{$questions}) {
                   7035:         my $question = $item;
                   7036:         my ($first,$count,$last);
                   7037:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7038:             $question = $1;
                   7039:             my $subquestion = $2;
                   7040:             $first = $first_bubble_line{$question-1} + 1;
                   7041:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7042:             my $subcount = 1;
                   7043:             while ($subcount<$subquestion) {
                   7044:                 $first += $subans[$subcount-1];
                   7045:                 $subcount ++;
                   7046:             }
                   7047:             $count = $subans[$subquestion-1];
                   7048:         } else {
                   7049: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7050: 	    $count   = $bubble_lines_per_response{$question-1};
                   7051:         }
1.506     raeburn  7052:         $last = $first+$count-1;
1.503     raeburn  7053:         push(@lines, ($first..$last));
1.497     foxr     7054:     }
                   7055:     return join(',', @lines);
                   7056: }
                   7057: 
                   7058: =pod 
                   7059: 
                   7060: =item prompt_for_corrections
                   7061: 
                   7062: Prompts for a potentially multiline correction to the
                   7063: user's bubbling (factors out common code from scantron_get_correction
                   7064: for multi and missing bubble cases).
                   7065: 
                   7066:  Arguments:
                   7067:    $r           - Apache request object.
                   7068:    $question    - The question number to prompt for.
                   7069:    $scan_config - The scantron file configuration hash.
                   7070:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7071:    $error       - Type of error
1.497     foxr     7072: 
                   7073:  Implicit inputs:
                   7074:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7075:                                   Numbered from 0 (but question numbers are from
                   7076:                                   1.
                   7077:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7078:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7079:                                   type problems render as separate sub-questions, 
1.503     raeburn  7080:                                   in exam mode. This hash contains a 
                   7081:                                   comma-separated list of the lines per 
                   7082:                                   sub-question.
1.510     raeburn  7083:    %responsetype_per_response   - essayresponse, formularesponse,
                   7084:                                   stringresponse, imageresponse, reactionresponse,
                   7085:                                   and organicresponse type problem parts can have
1.503     raeburn  7086:                                   multiple lines per response if the weight
                   7087:                                   assigned exceeds 10.  In this case, only
                   7088:                                   one bubble per line is permitted, but more 
                   7089:                                   than one line might contain bubbles, e.g.
                   7090:                                   bubbling of: line 1 - J, line 2 - J, 
                   7091:                                   line 3 - B would assign 22 points.  
1.497     foxr     7092: 
                   7093: =cut
                   7094: 
                   7095: sub prompt_for_corrections {
1.503     raeburn  7096:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7097:     my ($current_line,$lines);
                   7098:     my @linenums;
                   7099:     my $questionnum = $question;
                   7100:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7101:         $question = $1;
                   7102:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7103:         my $subquestion = $2;
                   7104:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7105:         my $subcount = 1;
                   7106:         while ($subcount<$subquestion) {
                   7107:             $current_line += $subans[$subcount-1];
                   7108:             $subcount ++;
                   7109:         }
                   7110:         $lines = $subans[$subquestion-1];
                   7111:     } else {
                   7112:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7113:         $lines        = $bubble_lines_per_response{$question-1};
                   7114:     }
1.497     foxr     7115:     if ($lines > 1) {
1.503     raeburn  7116:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7117:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7118:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7119:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7120:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7121:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7122:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.503     raeburn  7123:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their scantron sheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during scantron grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
                   7124:         } else {
                   7125:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7126:         }
1.497     foxr     7127:     }
                   7128:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7129:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7130: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7131: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7132:         push(@linenums,$current_line);
1.497     foxr     7133: 	$current_line++;
                   7134:     }
                   7135:     if ($lines > 1) {
                   7136: 	$r->print("<hr /><br />");
                   7137:     }
1.503     raeburn  7138:     return @linenums;
1.157     albertel 7139: }
1.423     albertel 7140: 
                   7141: =pod
                   7142: 
                   7143: =item scantron_bubble_selector
                   7144:   
                   7145:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7146:    possibly showing the existing the selected bubbles if known
1.423     albertel 7147: 
                   7148:  Arguments:
                   7149:     $r           - Apache request object
                   7150:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7151:     $line        - Number of the line being displayed.
1.503     raeburn  7152:     $questionnum - Question number (may include subquestion)
                   7153:     $error       - Type of error.
1.497     foxr     7154:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7155: 
                   7156: =cut
                   7157: 
1.157     albertel 7158: sub scantron_bubble_selector {
1.503     raeburn  7159:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7160:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7161: 
                   7162:     my $scmode=$$scan_config{'Qon'};
                   7163:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7164: 
1.157     albertel 7165:     my @alphabet=('A'..'Z');
1.503     raeburn  7166:     $r->print(&Apache::loncommon::start_data_table().
                   7167:               &Apache::loncommon::start_data_table_row());
                   7168:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7169:     for (my $i=0;$i<$max+1;$i++) {
                   7170: 	$r->print("\n".'<td align="center">');
                   7171: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7172: 	else { $r->print('&nbsp;'); }
                   7173: 	$r->print('</td>');
                   7174:     }
1.503     raeburn  7175:     $r->print(&Apache::loncommon::end_data_table_row().
                   7176:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7177:     for (my $i=0;$i<$max;$i++) {
                   7178: 	$r->print("\n".
                   7179: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7180: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7181:     }
1.503     raeburn  7182:     my $nobub_checked = ' ';
                   7183:     if ($error eq 'missingbubble') {
                   7184:         $nobub_checked = ' checked = "checked" ';
                   7185:     }
                   7186:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7187: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7188:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7189:               $line.'" value="'.$questionnum.'" /></td>');
                   7190:     $r->print(&Apache::loncommon::end_data_table_row().
                   7191:               &Apache::loncommon::end_data_table());
1.157     albertel 7192: }
                   7193: 
1.423     albertel 7194: =pod
                   7195: 
                   7196: =item num_matches
                   7197: 
1.424     albertel 7198:    Counts the number of characters that are the same between the two arguments.
                   7199: 
                   7200:  Arguments:
                   7201:    $orig - CODE from the scanline
                   7202:    $code - CODE to match against
                   7203: 
                   7204:  Returns:
                   7205:    $count - integer count of the number of same characters between the
                   7206:             two arguments
                   7207: 
1.423     albertel 7208: =cut
                   7209: 
1.194     albertel 7210: sub num_matches {
                   7211:     my ($orig,$code) = @_;
                   7212:     my @code=split(//,$code);
                   7213:     my @orig=split(//,$orig);
                   7214:     my $same=0;
                   7215:     for (my $i=0;$i<scalar(@code);$i++) {
                   7216: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7217:     }
                   7218:     return $same;
                   7219: }
                   7220: 
1.423     albertel 7221: =pod
                   7222: 
                   7223: =item scantron_get_closely_matching_CODEs
                   7224: 
1.424     albertel 7225:    Cycles through all CODEs and finds the set that has the greatest
                   7226:    number of same characters as the provided CODE
                   7227: 
                   7228:  Arguments:
                   7229:    $allcodes - hash ref returned by &get_codes()
                   7230:    $CODE     - CODE from the current scanline
                   7231: 
                   7232:  Returns:
                   7233:    2 element list
                   7234:     - first elements is number of how closely matching the best fit is 
                   7235:       (5 means best set has 5 matching characters)
                   7236:     - second element is an arrary ref containing the set of valid CODEs
                   7237:       that best fit the passed in CODE
                   7238: 
1.423     albertel 7239: =cut
                   7240: 
1.194     albertel 7241: sub scantron_get_closely_matching_CODEs {
                   7242:     my ($allcodes,$CODE)=@_;
                   7243:     my @CODEs;
                   7244:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7245: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7246:     }
                   7247: 
                   7248:     return ($#CODEs,$CODEs[-1]);
                   7249: }
                   7250: 
1.423     albertel 7251: =pod
                   7252: 
                   7253: =item get_codes
                   7254: 
1.424     albertel 7255:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7256:    set of remembered CODEs.
                   7257: 
                   7258:  Arguments:
                   7259:   $old_name - name of the set of remembered CODEs
                   7260:   $cdom     - domain of the course
                   7261:   $cnum     - internal course name
                   7262: 
                   7263:  Returns:
                   7264:   %allcodes - keys are the valid CODEs, values are all 1
                   7265: 
1.423     albertel 7266: =cut
                   7267: 
1.194     albertel 7268: sub get_codes {
1.280     foxr     7269:     my ($old_name, $cdom, $cnum) = @_;
                   7270:     if (!$old_name) {
                   7271: 	$old_name=$env{'form.scantron_CODElist'};
                   7272:     }
                   7273:     if (!$cdom) {
                   7274: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7275:     }
                   7276:     if (!$cnum) {
                   7277: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7278:     }
1.278     albertel 7279:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7280: 				    $cdom,$cnum);
                   7281:     my %allcodes;
                   7282:     if ($result{"type\0$old_name"} eq 'number') {
                   7283: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7284:     } else {
                   7285: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7286:     }
1.194     albertel 7287:     return %allcodes;
                   7288: }
                   7289: 
1.423     albertel 7290: =pod
                   7291: 
                   7292: =item scantron_validate_CODE
                   7293: 
1.424     albertel 7294:    Validates all scanlines in the selected file to not have any
                   7295:    invalid or underspecified CODEs and that none of the codes are
                   7296:    duplicated if this was requested.
                   7297: 
1.423     albertel 7298: =cut
                   7299: 
1.157     albertel 7300: sub scantron_validate_CODE {
                   7301:     my ($r,$currentphase) = @_;
1.257     albertel 7302:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7303:     if ($scantron_config{'CODElocation'} &&
                   7304: 	$scantron_config{'CODEstart'} &&
                   7305: 	$scantron_config{'CODElength'}) {
1.257     albertel 7306: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7307: 	    &FIXME_blow_up()
                   7308: 	}
                   7309:     } else {
                   7310: 	return (0,$currentphase+1);
                   7311:     }
                   7312:     
                   7313:     my %usedCODEs;
                   7314: 
1.194     albertel 7315:     my %allcodes=&get_codes();
1.186     albertel 7316: 
1.447     foxr     7317:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   7318: 
1.186     albertel 7319:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7320:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7321: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7322: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7323: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7324: 						 $scan_data);
                   7325: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7326: 	my $error=0;
1.224     albertel 7327: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7328: 	    &scantron_get_correction($r,$i,$scan_record,
                   7329: 				     \%scantron_config,
                   7330: 				     $line,'incorrectCODE',\%allcodes);
                   7331: 	    return(1,$currentphase);
                   7332: 	}
1.221     albertel 7333: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7334: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7335: 	    &scantron_get_correction($r,$i,$scan_record,
                   7336: 				     \%scantron_config,
1.194     albertel 7337: 				     $line,'incorrectCODE',\%allcodes);
                   7338: 	    return(1,$currentphase);
1.186     albertel 7339: 	}
1.214     albertel 7340: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7341: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7342: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7343: 	    &scantron_get_correction($r,$i,$scan_record,
                   7344: 				     \%scantron_config,
1.194     albertel 7345: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7346: 	    return(1,$currentphase);
1.186     albertel 7347: 	}
1.524     raeburn  7348: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7349:     }
1.157     albertel 7350:     return (0,$currentphase+1);
                   7351: }
                   7352: 
1.423     albertel 7353: =pod
                   7354: 
                   7355: =item scantron_validate_doublebubble
                   7356: 
1.424     albertel 7357:    Validates all scanlines in the selected file to not have any
                   7358:    bubble lines with multiple bubbles marked.
                   7359: 
1.423     albertel 7360: =cut
                   7361: 
1.157     albertel 7362: sub scantron_validate_doublebubble {
                   7363:     my ($r,$currentphase) = @_;
                   7364:     #get student info
                   7365:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7366:     my %idmap=&username_to_idmap($classlist);
                   7367: 
                   7368:     #get scantron line setup
1.257     albertel 7369:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7370:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     7371:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   7372: 
1.157     albertel 7373:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7374: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7375: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7376: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7377: 						 $scan_data);
                   7378: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7379: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7380: 				 'doublebubble',
                   7381: 				 $$scan_record{'scantron.doubleerror'});
                   7382:     	return (1,$currentphase);
                   7383:     }
                   7384:     return (0,$currentphase+1);
                   7385: }
                   7386: 
1.423     albertel 7387: 
1.503     raeburn  7388: sub scantron_get_maxbubble {
1.257     albertel 7389:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7390: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7391: 	&restore_bubble_lines();
1.257     albertel 7392: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7393:     }
1.330     albertel 7394: 
1.447     foxr     7395:     my (undef, undef, $sequence) =
1.257     albertel 7396: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7397: 
1.447     foxr     7398:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 7399:     my $map=$navmap->getResourceByUrl($sequence);
                   7400:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7401: 
                   7402:     &Apache::lonxml::clear_problem_counter();
                   7403: 
1.435     foxr     7404:     my $uname       = $env{'form.student'};
                   7405:     my $udom        = $env{'form.userdom'};
                   7406:     my $cid         = $env{'request.course.id'};
                   7407:     my $total_lines = 0;
                   7408:     %bubble_lines_per_response = ();
1.447     foxr     7409:     %first_bubble_line         = ();
1.503     raeburn  7410:     %subdivided_bubble_lines   = ();
                   7411:     %responsetype_per_response = ();
1.447     foxr     7412:   
                   7413:     my $response_number = 0;
                   7414:     my $bubble_line     = 0;
1.191     albertel 7415:     foreach my $resource (@resources) {
1.515     raeburn  7416:         my $symb = $resource->symb();
1.523     raeburn  7417: 
                   7418:         my (@parts,@allparts,@possible_parts);
                   7419: 
1.510     raeburn  7420:         # Need to retrieve part IDs and response IDs because essayresponse,
                   7421:         # reactionresponse and organicresponse items are not included in 
                   7422:         # $analysis{'parts'} from lonnet::ssi.  
1.523     raeburn  7423:         if (ref($resource->parts()) eq 'ARRAY') {
1.503     raeburn  7424:             foreach my $part (@{$resource->parts()}) {
1.515     raeburn  7425:                 if (!&Apache::loncommon::check_if_partid_hidden($part,$symb,$udom,$uname)) {
                   7426:                     my @resp_ids = $resource->responseIds($part);
                   7427:                     foreach my $id (@resp_ids) {
1.523     raeburn  7428:                         my $part_id = $part.'.'.$id;
                   7429:                         push(@possible_parts,$part_id);
1.515     raeburn  7430:                     }
1.503     raeburn  7431:                 }
                   7432:             }
                   7433:         }
1.435     foxr     7434: 
1.523     raeburn  7435:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
                   7436:                                         ('symb' => $symb,
                   7437:                                          'grade_target' => 'analyze',
                   7438:                                          'grade_courseid' => $cid,
                   7439:                                          'grade_domain' => $udom,
                   7440:                                          'grade_username' => $uname));
                   7441:         my (undef, $an) =
                   7442:             split(/_HASH_REF__/,$result, 2);
1.503     raeburn  7443: 
1.435     foxr     7444: 	my %analysis = &Apache::lonnet::str2hash($an);
                   7445: 
1.503     raeburn  7446:         if (ref($analysis{'parts'}) eq 'ARRAY') {
1.515     raeburn  7447:             foreach my $part (@{$analysis{'parts'}}) {
                   7448:                 my ($id,$respid) = split(/\./,$part);
                   7449:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                   7450:                     push(@parts,$part);
                   7451:                 }
                   7452:             }
1.503     raeburn  7453:         }
1.523     raeburn  7454:         # Add part_ids for any essayresponse, reactionresponse or 
                   7455:         # organicresponse items. 
                   7456:         foreach my $part_id (@possible_parts) {
                   7457:             if (grep(/^\Q$part_id\E$/,@parts)) {
                   7458:                 push(@allparts,$part_id);
                   7459:             } else {
                   7460:                 if (($analysis{$part_id.'.type'} eq 'essayresponse') ||
                   7461:                     ($analysis{$part_id.'.type'} eq 'reactionresponse') ||
                   7462:                     ($analysis{$part_id.'.type'} eq 'organicresponse')) {
1.524     raeburn  7463:                     push(@allparts,$part_id);
1.503     raeburn  7464:                 }
                   7465:             }
                   7466:         }
1.435     foxr     7467: 
1.523     raeburn  7468: 	foreach my $part_id (@allparts) {
                   7469:             my $lines;
1.447     foxr     7470: 
                   7471: 	    # TODO - make this a persistent hash not an array.
                   7472: 
1.509     raeburn  7473:             # optionresponse, matchresponse and rankresponse type items 
                   7474:             # render as separate sub-questions in exam mode.
1.503     raeburn  7475:             if (($analysis{$part_id.'.type'} eq 'optionresponse') ||
1.509     raeburn  7476:                 ($analysis{$part_id.'.type'} eq 'matchresponse') ||
                   7477:                 ($analysis{$part_id.'.type'} eq 'rankresponse')) {
1.503     raeburn  7478:                 my ($numbub,$numshown);
                   7479:                 if ($analysis{$part_id.'.type'} eq 'optionresponse') {
                   7480:                     if (ref($analysis{$part_id.'.options'}) eq 'ARRAY') {
                   7481:                         $numbub = scalar(@{$analysis{$part_id.'.options'}});
                   7482:                     }
                   7483:                 } elsif ($analysis{$part_id.'.type'} eq 'matchresponse') {
                   7484:                     if (ref($analysis{$part_id.'.items'}) eq 'ARRAY') {
                   7485:                         $numbub = scalar(@{$analysis{$part_id.'.items'}});
                   7486:                     }
1.509     raeburn  7487:                 } elsif ($analysis{$part_id.'.type'} eq 'rankresponse') {
                   7488:                     if (ref($analysis{$part_id.'.foils'}) eq 'ARRAY') {
                   7489:                         $numbub = scalar(@{$analysis{$part_id.'.foils'}});
                   7490:                     }
1.503     raeburn  7491:                 }
                   7492:                 if (ref($analysis{$part_id.'.shown'}) eq 'ARRAY') {
                   7493:                     $numshown = scalar(@{$analysis{$part_id.'.shown'}});
                   7494:                 }
                   7495:                 my $bubbles_per_line = 10;
1.523     raeburn  7496:                 my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7497:                 if (($numbub % $bubbles_per_line) != 0) {
1.503     raeburn  7498:                     $inner_bubble_lines++;
                   7499:                 }
                   7500:                 for (my $i=0; $i<$numshown; $i++) {
                   7501:                     $subdivided_bubble_lines{$response_number} .= 
                   7502:                         $inner_bubble_lines.',';
                   7503:                 }
                   7504:                 $subdivided_bubble_lines{$response_number} =~ s/,$//;
1.523     raeburn  7505:                 $lines = $numshown * $inner_bubble_lines;
                   7506:             } else {
                   7507:                 $lines = $analysis{"$part_id.bubble_lines"};
1.503     raeburn  7508:             } 
1.447     foxr     7509: 
1.503     raeburn  7510:             $first_bubble_line{$response_number} = $bubble_line;
                   7511: 	    $bubble_lines_per_response{$response_number} = $lines;
                   7512:             $responsetype_per_response{$response_number} = 
                   7513:                 $analysis{$part_id.'.type'};
1.447     foxr     7514: 	    $response_number++;
                   7515: 
                   7516: 	    $bubble_line +=  $lines;
                   7517: 	    $total_lines +=  $lines;
1.435     foxr     7518: 	}
                   7519: 
1.191     albertel 7520:     }
                   7521:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     7522: 
                   7523:     &save_bubble_lines();
1.330     albertel 7524:     $env{'form.scantron_maxbubble'} =
1.435     foxr     7525: 	$total_lines;
1.257     albertel 7526:     return $env{'form.scantron_maxbubble'};
1.191     albertel 7527: }
                   7528: 
1.423     albertel 7529: 
1.157     albertel 7530: sub scantron_validate_missingbubbles {
                   7531:     my ($r,$currentphase) = @_;
                   7532:     #get student info
                   7533:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7534:     my %idmap=&username_to_idmap($classlist);
                   7535: 
                   7536:     #get scantron line setup
1.257     albertel 7537:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7538:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7539:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7540:     if (!$max_bubble) { $max_bubble=2**31; }
                   7541:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7542: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7543: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7544: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7545: 						 $scan_data);
                   7546: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7547: 	my @to_correct;
1.470     foxr     7548: 	
                   7549: 	# Probably here's where the error is...
                   7550: 
1.157     albertel 7551: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7552:             my $lastbubble;
                   7553:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7554:                my $question = $1;
                   7555:                my $subquestion = $2;
                   7556:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7557:                my $first = $first_bubble_line{$question-1};
                   7558:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7559:                my $subcount = 1;
                   7560:                while ($subcount<$subquestion) {
                   7561:                    $first += $subans[$subcount-1];
                   7562:                    $subcount ++;
                   7563:                }
                   7564:                my $count = $subans[$subquestion-1];
                   7565:                $lastbubble = $first + $count;
                   7566:             } else {
                   7567:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7568:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7569:             }
                   7570:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7571: 	    push(@to_correct,$missing);
                   7572: 	}
                   7573: 	if (@to_correct) {
                   7574: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7575: 				     $line,'missingbubble',\@to_correct);
                   7576: 	    return (1,$currentphase);
                   7577: 	}
                   7578: 
                   7579:     }
                   7580:     return (0,$currentphase+1);
                   7581: }
                   7582: 
1.423     albertel 7583: 
1.82      albertel 7584: sub scantron_process_students {
1.75      albertel 7585:     my ($r) = @_;
1.513     foxr     7586: 
1.257     albertel 7587:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7588:     my ($symb)=&get_symb($r);
1.513     foxr     7589:     if (!$symb) {
                   7590: 	return '';
                   7591:     }
1.324     albertel 7592:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7593: 
1.257     albertel 7594:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7595:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7596:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7597:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7598:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7599:     my $map=$navmap->getResourceByUrl($sequence);
                   7600:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 7601: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 7602:     my $result= <<SCANTRONFORM;
1.81      albertel 7603: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7604:   <input type="hidden" name="command" value="scantron_configphase" />
                   7605:   $default_form_data
                   7606: SCANTRONFORM
1.82      albertel 7607:     $r->print($result);
                   7608: 
                   7609:     my @delayqueue;
1.140     albertel 7610:     my %completedstudents;
                   7611:     
1.520     www      7612:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7613:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7614:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7615:  				    'Scantron Progress',$count,
1.195     albertel 7616: 				    'inline',undef,'scantronupload');
1.140     albertel 7617:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7618: 					  'Processing first student');
                   7619:     my $start=&Time::HiRes::time();
1.158     albertel 7620:     my $i=-1;
1.200     albertel 7621:     my ($uname,$udom,$started);
1.447     foxr     7622: 
                   7623:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
1.513     foxr     7624:     
                   7625: 
                   7626:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7627:     # the user and return.
                   7628: 
                   7629:     if ($ssi_error) {
                   7630: 	$r->print("</form>");
                   7631: 	&ssi_print_error($r);
                   7632: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7633:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7634: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7635:     }
1.447     foxr     7636: 
1.157     albertel 7637:     while ($i<$scanlines->{'count'}) {
                   7638:  	($uname,$udom)=('','');
                   7639:  	$i++;
1.200     albertel 7640:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7641:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7642: 	if ($started) {
                   7643: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7644: 						     'last student');
                   7645: 	}
                   7646: 	$started=1;
1.157     albertel 7647:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7648:  						 $scan_data);
                   7649:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7650:  					      \%idmap,$i)) {
                   7651:   	    &scantron_add_delay(\@delayqueue,$line,
                   7652:  				'Unable to find a student that matches',1);
                   7653:  	    next;
                   7654:   	}
                   7655:  	if (exists $completedstudents{$uname}) {
                   7656:  	    &scantron_add_delay(\@delayqueue,$line,
                   7657:  				'Student '.$uname.' has multiple sheets',2);
                   7658:  	    next;
                   7659:  	}
                   7660:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7661: 
                   7662: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7663:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7664: 
                   7665: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7666: 	    &scantron_putfile($scanlines,$scan_data);
                   7667: 	}
1.161     albertel 7668: 	
                   7669: 	my $i=0;
1.83      albertel 7670: 	foreach my $resource (@resources) {
1.85      albertel 7671: 	    $i++;
1.193     albertel 7672: 	    my %form=('submitted'     =>'scantron',
                   7673: 		      'grade_target'  =>'grade',
                   7674: 		      'grade_username'=>$uname,
                   7675: 		      'grade_domain'  =>$udom,
1.257     albertel 7676: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 7677: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 7678: 	    if (exists($scan_record->{'scantron.CODE'})
                   7679: 		&& 
                   7680: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 7681: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 7682: 	    } else {
                   7683: 		$form{'CODE'}='';
1.513     foxr     7684: 	    } 
                   7685: 	    my $result=&ssi_with_retries($resource->src(), $ssi_retries, %form);
                   7686: 	    if ($ssi_error) {
                   7687: 		$ssi_error = 0;	# So end of handler error message does not trigger.
                   7688: 		$r->print("</form>");
                   7689: 		&ssi_print_error($r);
                   7690: 		$r->print(&show_grading_menu_form($symb));
1.520     www      7691:                 &Apache::lonnet::remove_lock($lock);
1.513     foxr     7692: 		return '';	# Why return ''?  Beats me.
1.193     albertel 7693: 	    }
1.513     foxr     7694: 
1.213     albertel 7695: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7696: 	}
1.140     albertel 7697: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7698: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7699:     } continue {
1.330     albertel 7700: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7701: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7702:     }
1.140     albertel 7703:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7704:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7705: #    my $lasttime = &Time::HiRes::time()-$start;
                   7706: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7707: 
1.200     albertel 7708:     $r->print("</form>");
1.324     albertel 7709:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7710:     return '';
1.75      albertel 7711: }
1.157     albertel 7712: 
                   7713: sub scantron_upload_scantron_data {
                   7714:     my ($r)=@_;
1.257     albertel 7715:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7716:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7717: 							  'domainid',
                   7718: 							  'coursename');
1.257     albertel 7719:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7720: 						   'domainid');
1.324     albertel 7721:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7722:     $r->print('
1.157     albertel 7723: <script type="text/javascript" language="javascript">
                   7724:     function checkUpload(formname) {
                   7725: 	if (formname.upfile.value == "") {
                   7726: 	    alert("Please use the browse button to select a file from your local directory.");
                   7727: 	    return false;
                   7728: 	}
                   7729: 	formname.submit();
                   7730:     }
                   7731: </script>
                   7732: 
1.492     albertel 7733: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7734: '.$default_form_data.'
1.181     albertel 7735: <table>
1.492     albertel 7736: <tr><td>'.$select_link.'                             </td></tr>
                   7737: <tr><td>'.&mt('Course ID:').'     </td>
                   7738:     <td><input name="courseid"   type="text" />      </td></tr>
                   7739: <tr><td>'.&mt('Course Name:').'   </td>
                   7740:     <td><input name="coursename" type="text" />      </td></tr>
                   7741: <tr><td>'.&mt('Domain:').'        </td>
                   7742:     <td>'.$domsel.'                                  </td></tr>
                   7743: <tr><td>'.&mt('File to upload:').'</td>
                   7744:     <td><input type="file" name="upfile" size="50" /></td></tr>
1.181     albertel 7745: </table>
1.492     albertel 7746: <input name="command" value="scantronupload_save" type="hidden" />
                   7747: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.157     albertel 7748: </form>
1.492     albertel 7749: ');
1.157     albertel 7750:     return '';
                   7751: }
                   7752: 
1.423     albertel 7753: 
1.157     albertel 7754: sub scantron_upload_scantron_data_save {
                   7755:     my($r)=@_;
1.324     albertel 7756:     my ($symb)=&get_symb($r,1);
1.182     albertel 7757:     my $doanotherupload=
                   7758: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7759: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7760: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7761: 	'</form>'."\n";
1.257     albertel 7762:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7763: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7764: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.492     albertel 7765: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
1.182     albertel 7766: 	if ($symb) {
1.324     albertel 7767: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7768: 	} else {
                   7769: 	    $r->print($doanotherupload);
                   7770: 	}
1.162     albertel 7771: 	return '';
                   7772:     }
1.257     albertel 7773:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.492     albertel 7774:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
1.257     albertel 7775:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7776:     #FIXME
                   7777:     #copied from lonnet::userfileupload()
                   7778:     #make that function able to target a specified course
                   7779:     # Replace Windows backslashes by forward slashes
                   7780:     $fname=~s/\\/\//g;
                   7781:     # Get rid of everything but the actual filename
                   7782:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7783:     # Replace spaces by underscores
                   7784:     $fname=~s/\s+/\_/g;
                   7785:     # Replace all other weird characters by nothing
                   7786:     $fname=~s/[^\w\.\-]//g;
                   7787:     # See if there is anything left
                   7788:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7789:     my $uploadedfile=$fname;
1.157     albertel 7790:     $fname='scantron_orig_'.$fname;
1.257     albertel 7791:     if (length($env{'form.upfile'}) < 2) {
1.492     albertel 7792: 	$r->print(&mt("<span class=\"LC_error\">Error:</span> The file you attempted to upload, [_1]  contained no information. Please check that you entered the correct filename.",'<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
1.183     albertel 7793:     } else {
1.275     albertel 7794: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7795: 	if ($result =~ m|^/uploaded/|) {
1.492     albertel 7796: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
                   7797: 			  (length($env{'form.upfile'})-1),
                   7798: 			  '<span class="LC_filename">'.$result."</span>"));
1.210     albertel 7799: 	} else {
1.492     albertel 7800: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
                   7801: 			  $result,
                   7802: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
                   7803: 
1.183     albertel 7804: 	}
                   7805:     }
1.174     albertel 7806:     if ($symb) {
1.209     ng       7807: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7808:     } else {
1.182     albertel 7809: 	$r->print($doanotherupload);
1.174     albertel 7810:     }
1.157     albertel 7811:     return '';
                   7812: }
                   7813: 
1.202     albertel 7814: sub valid_file {
                   7815:     my ($requested_file)=@_;
                   7816:     foreach my $filename (sort(&scantron_filenames())) {
                   7817: 	if ($requested_file eq $filename) { return 1; }
                   7818:     }
                   7819:     return 0;
                   7820: }
                   7821: 
                   7822: sub scantron_download_scantron_data {
                   7823:     my ($r)=@_;
1.324     albertel 7824:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7825:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7826:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7827:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7828:     if (! &valid_file($file)) {
1.492     albertel 7829: 	$r->print('
1.202     albertel 7830: 	<p>
1.492     albertel 7831: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7832:         </p>
1.492     albertel 7833: ');
1.324     albertel 7834: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7835: 	return;
                   7836:     }
                   7837:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7838:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7839:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7840:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7841:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7842:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7843:     $r->print('
1.202     albertel 7844:     <p>
1.492     albertel 7845: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7846: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7847:     </p>
                   7848:     <p>
1.492     albertel 7849: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7850: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7851:     </p>
                   7852:     <p>
1.492     albertel 7853: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7854: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7855:     </p>
1.492     albertel 7856: ');
1.324     albertel 7857:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7858:     return '';
                   7859: }
1.157     albertel 7860: 
1.523     raeburn  7861: sub checkscantron_results {
                   7862:     my ($r) = @_;
                   7863:     my ($symb)=&get_symb($r);
                   7864:     if (!$symb) {return '';}
                   7865:     my $grading_menu_button=&show_grading_menu_form($symb);
                   7866:     my $cid = $env{'request.course.id'};
                   7867:     my %lettdig = (
                   7868:                     A => 1,
                   7869:                     B => 2,
                   7870:                     C => 3,
                   7871:                     D => 4,
                   7872:                     E => 5,
                   7873:                     F => 6,
                   7874:                     G => 7,
                   7875:                     H => 8,
                   7876:                     I => 9,
                   7877:                     J => 0,
                   7878:                   );
                   7879:     my $numletts = scalar(keys(%lettdig));
                   7880:     my $cnum = $env{'course.'.$cid.'.num'};
                   7881:     my $cdom = $env{'course.'.$cid.'.domain'};
                   7882:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7883:     my %record;
                   7884:     my %scantron_config =
                   7885:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   7886:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   7887:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7888:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   7889:     my $navmap=Apache::lonnavmaps::navmap->new();
                   7890:     my $map=$navmap->getResourceByUrl($sequence);
                   7891:     my @resources=$navmap->retrieveResources($map,undef,1,0);
                   7892:     my (%scandata,%lastname,%bylast);
                   7893:     $r->print('
                   7894: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   7895: 
                   7896:     my @delayqueue;
                   7897:     my %completedstudents;
                   7898: 
                   7899:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
                   7900:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
                   7901:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
                   7902:                                     'inline',undef,'checkscantron');
                   7903:     my ($username,$domain,$uname,$started);
                   7904: 
                   7905:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
                   7906: 
                   7907:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7908:                                           'Processing first student');
                   7909:     my $start=&Time::HiRes::time();
                   7910:     my $i=-1;
                   7911: 
                   7912:     while ($i<$scanlines->{'count'}) {
                   7913:         ($username,$domain,$uname)=('','','');
                   7914:         $i++;
                   7915:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   7916:         if ($line=~/^[\s\cz]*$/) { next; }
                   7917:         if ($started) {
                   7918:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7919:                                                      'last student');
                   7920:         }
                   7921:         $started=1;
                   7922:         my $scan_record=
                   7923:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   7924:                                                      $scan_data);
                   7925:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   7926:                                                               \%idmap,$i)) {
                   7927:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7928:                                 'Unable to find a student that matches',1);
                   7929:             next;
                   7930:         }
                   7931:         if (exists $completedstudents{$uname}) {
                   7932:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7933:                                 'Student '.$uname.' has multiple sheets',2);
                   7934:             next;
                   7935:         }
                   7936:         my $pid = $scan_record->{'scantron.ID'};
                   7937:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   7938:         push(@{$bylast{$lastname{$pid}}},$pid);
                   7939:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7940:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7941:         chomp($scandata{$pid});
                   7942:         $scandata{$pid} =~ s/\r$//;
                   7943:         ($username,$domain)=split(/:/,$uname);
                   7944:         my $counter = -1;
                   7945:         my (%expected,%startpos);
                   7946:         foreach my $resource (@resources) {
                   7947:             next if (!$resource->is_problem());
                   7948:             my $symb = $resource->symb();
                   7949:             my $partsref = $resource->parts();
                   7950:             my @parts;
                   7951:             my @part_ids = ();
                   7952:             if (ref($partsref) eq 'ARRAY') {
                   7953:                @parts = @{$partsref};
                   7954:                foreach my $part (@parts) {
                   7955:                    my @resp_ids = $resource->responseIds($part);
                   7956:                    foreach my $resp (@resp_ids) {
                   7957:                        $counter ++;
                   7958:                        my $part_id = $part.'.'.$resp;
                   7959:                        $expected{$part_id} = 0;
                   7960:                        push(@part_ids,$part_id);
                   7961:                        if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   7962:                            my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   7963:                            foreach my $item (@sub_lines) {
                   7964:                                $expected{$part_id} += $item;
                   7965:                            }
                   7966:                        } else {
                   7967:                            $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   7968:                        }
                   7969:                        $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   7970:                    }
                   7971:                 }
                   7972:             }
                   7973:             if ($symb) {
                   7974:                 my %recorded;
                   7975:                 my (%returnhash) =
                   7976:                     &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   7977:                 if ($returnhash{'version'}) {
                   7978:                     my %lasthash=();
                   7979:                     my $version;
                   7980:                     for ($version=1;$version<=$returnhash{'version'};$version++) {
                   7981:                         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   7982:                             $lasthash{$key}=$returnhash{$version.':'.$key};
                   7983:                         }
                   7984:                     }
                   7985:                     foreach my $key (keys(%lasthash)) {
                   7986:                         if ($key =~ /\.scantron$/) {
                   7987:                             my $value = &unescape($lasthash{$key});
                   7988:                             my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   7989:                             if ($value eq '') {
                   7990:                                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   7991:                                     for (my $j=0; $j<$scantron_config{'length'}; $j++) {
                   7992:                                         $recorded{$part_id} .= $;
                   7993:                                     }
                   7994:                                 }
                   7995:                             } else {
                   7996:                                 my @tocheck;
                   7997:                                 my @items = split(//,$value);
                   7998:                                 if (($scantron_config{'Qon'} eq 'letter') ||
                   7999:                                     ($scantron_config{'Qon'} eq 'number')) {
                   8000:                                     if (@items < $expected{$part_id}) {
                   8001:                                         my $fragment = substr($scandata{$pid},$startpos{$part_id},$expected{$part_id});
                   8002:                                         my @singles = split(//,$fragment);
                   8003:                                         foreach my $pos (@singles) {
                   8004:                                             if ($pos eq ' ') {
                   8005:                                                 push(@tocheck,$pos);
                   8006:                                             } else {
                   8007:                                                 my $next = shift(@items);
                   8008:                                                 push(@tocheck,$next);
                   8009:                                             }
                   8010:                                         }
                   8011:                                     } else {
                   8012:                                         @tocheck = @items;
                   8013:                                     }
                   8014:                                     foreach my $letter (@tocheck) {
                   8015:                                         if ($scantron_config{'Qon'} eq 'letter') {
                   8016:                                             if ($letter !~ /^[A-J]$/) {
                   8017:                                                 $letter = $scantron_config{'Qoff'};
                   8018:                                             }
                   8019:                                             $recorded{$part_id} .= $letter;
                   8020:                                         } elsif ($scantron_config{'Qon'} eq 'number') {
                   8021:                                             my $digit;
                   8022:                                             if ($letter !~ /^[A-J]$/) {
                   8023:                                                 $digit = $scantron_config{'Qoff'};
                   8024:                                             } else {
                   8025:                                                 $digit = $lettdig{$letter};
                   8026:                                             }
                   8027:                                             $recorded{$part_id} .= $digit;
                   8028:                                         }
                   8029:                                     }
                   8030:                                 } else {
                   8031:                                     @tocheck = @items;
                   8032:                                     for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8033:                                         my $curr_sub = shift(@tocheck);
                   8034:                                         my $digit;
                   8035:                                         if ($curr_sub =~ /^[A-J]$/) {
                   8036:                                             $digit = $lettdig{$curr_sub}-1;
                   8037:                                         }
                   8038:                                         if ($curr_sub eq 'J') {
                   8039:                                             $digit += scalar($numletts);
                   8040:                                         }
                   8041:                                         for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
                   8042:                                             if ($j == $digit) {
                   8043:                                                 $recorded{$part_id} .= $scantron_config{'Qon'};
                   8044:                                             } else {
                   8045:                                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
                   8046:                                             }
                   8047:                                         }
                   8048:                                     }
                   8049:                                 }
                   8050:                             }
                   8051:                         }
                   8052:                     }
                   8053:                 }
                   8054:                 foreach my $part_id (@part_ids) {
                   8055:                     if ($recorded{$part_id} eq '') {
                   8056:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8057:                             for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
                   8058:                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
                   8059:                             }
                   8060:                         }
                   8061:                     }
                   8062:                     $record{$pid} .= $recorded{$part_id};
                   8063:                 }
                   8064:             }
                   8065:         }
                   8066:     }
                   8067:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8068:     $r->print('<br />');
                   8069:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8070:     $passed = 0;
                   8071:     $failed = 0;
                   8072:     $numstudents = 0;
                   8073:     foreach my $last (sort(keys(%bylast))) {
                   8074:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8075:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8076:                 my $showscandata = $scandata{$pid};
                   8077:                 my $showrecord = $record{$pid};
                   8078:                 $showscandata =~ s/\s/&nbsp;/g;
                   8079:                 $showrecord =~ s/\s/&nbsp;/g;
                   8080:                 if ($scandata{$pid} eq $record{$pid}) {
                   8081:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8082:                     $okstudents .= '<tr class="'.$css_class.'">'.
                   8083: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8084: '</tr>'."\n".
                   8085: '<tr class="'.$css_class.'">'."\n".
                   8086: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8087:                     $passed ++;
                   8088:                 } else {
                   8089:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
                   8090:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8091: '</tr>'."\n".
                   8092: '<tr class="'.$css_class.'">'."\n".
                   8093: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8094: '</tr>'."\n";
                   8095:                     $failed ++;
                   8096:                 }
                   8097:                 $numstudents ++;
                   8098:             }
                   8099:         }
                   8100:     }
                   8101:     $r->print('<p>'.&mt('Comparison of scantron data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
                   8102:     $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>');
                   8103:     if ($passed) {
                   8104:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
                   8105:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8106:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8107:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8108:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8109:                  $okstudents."\n".
                   8110:                  &Apache::loncommon::end_data_table().'<br />');
                   8111:     }
                   8112:     if ($failed) {
                   8113:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
                   8114:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8115:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8116:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8117:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8118:                  $badstudents."\n".
                   8119:                  &Apache::loncommon::end_data_table()).'<br />'.
                   8120:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
                   8121:     }
                   8122:     $r->print('</form><br />'.$grading_menu_button);
                   8123:     return;
                   8124: }
                   8125: 
1.423     albertel 8126: 
1.75      albertel 8127: #-------- end of section for handling grading scantron forms -------
                   8128: #
                   8129: #-------------------------------------------------------------------
                   8130: 
1.72      ng       8131: #-------------------------- Menu interface -------------------------
                   8132: #
                   8133: #--- Show a Grading Menu button - Calls the next routine ---
                   8134: sub show_grading_menu_form {
1.324     albertel 8135:     my ($symb)=@_;
1.125     ng       8136:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8137: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8138: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8139: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8140: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8141: 	'</form>'."\n";
                   8142:     return $result;
                   8143: }
                   8144: 
1.77      ng       8145: # -- Retrieve choices for grading form
                   8146: sub savedState {
                   8147:     my %savedState = ();
1.257     albertel 8148:     if ($env{'form.saveState'}) {
                   8149: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8150: 	    my ($key,$value) = split(/=/,$_,2);
                   8151: 	    $savedState{$key} = $value;
                   8152: 	}
                   8153:     }
                   8154:     return \%savedState;
                   8155: }
1.76      ng       8156: 
1.443     banghart 8157: sub grading_menu {
                   8158:     my ($request) = @_;
                   8159:     my ($symb)=&get_symb($request);
                   8160:     if (!$symb) {return '';}
                   8161:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8162:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8163: 
1.444     banghart 8164:     $request->print($table);
1.443     banghart 8165:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8166:                   'handgrade'=>$hdgrade,
                   8167:                   'probTitle'=>$probTitle,
                   8168:                   'command'=>'submit_options',
                   8169:                   'saveState'=>"",
                   8170:                   'gradingMenu'=>1,
                   8171:                   'showgrading'=>"yes");
                   8172:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8173:     my @menu = ({ url => $url,
                   8174:                      name => &mt('Manual Grading/View Submissions'),
                   8175:                      short_description => 
                   8176:     &mt('Start the process of hand grading submissions.'),
                   8177:                  });
                   8178:     $fields{'command'} = 'csvform';
                   8179:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8180:     push(@menu, { url => $url,
1.443     banghart 8181:                    name => &mt('Upload Scores'),
                   8182:                    short_description => 
                   8183:             &mt('Specify a file containing the class scores for current resource.')});
                   8184:     $fields{'command'} = 'processclicker';
                   8185:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8186:     push(@menu, { url => $url,
1.443     banghart 8187:                    name => &mt('Process Clicker'),
                   8188:                    short_description => 
                   8189:             &mt('Specify a file containing the clicker information for this resource.')});
                   8190:     $fields{'command'} = 'scantron_selectphase';
                   8191:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8192:     push(@menu, { url => $url,
1.523     raeburn  8193:                    name => &mt('Grade/Manage/Review Scantron Forms'),
1.454     banghart 8194:                    short_description => 
1.523     raeburn  8195:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
1.443     banghart 8196:     $fields{'command'} = 'verify';
                   8197:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8198:     push(@menu, { url => "",
1.443     banghart 8199:                    name => &mt('Verify Receipt'),
                   8200:                    short_description => 
                   8201:             &mt('')});
                   8202:     #
                   8203:     # Create the menu
                   8204:     my $Str;
1.444     banghart 8205:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8206:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8207:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8208:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8209: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8210: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8211: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8212: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8213: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8214: 
1.443     banghart 8215:     foreach my $menudata (@menu) {
1.445     banghart 8216:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   8217:             $Str .='    <h3><a '.
                   8218:                 $menudata->{'jscript'}.
                   8219:                 ' href="'.
                   8220:                 $menudata->{'url'}.'" >'.
                   8221:                 $menudata->{'name'}."</a></h3>\n";
                   8222:         } else {
1.511     www      8223:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
1.445     banghart 8224:                 $menudata->{'jscript'}.
1.458     banghart 8225:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.511     www      8226:                 ' /> '.
                   8227: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
                   8228:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 8229:         }
1.443     banghart 8230:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   8231:             "\n";
                   8232:     }
1.444     banghart 8233:     $Str .="</form>\n";
1.443     banghart 8234:     $request->print(<<GRADINGMENUJS);
                   8235: <script type="text/javascript" language="javascript">
                   8236:     function checkChoice(formname,val,cmdx) {
                   8237: 	if (val <= 2) {
                   8238: 	    var cmd = radioSelection(formname.radioChoice);
                   8239: 	    var cmdsave = cmd;
                   8240: 	} else {
                   8241: 	    cmd = cmdx;
                   8242: 	    cmdsave = 'submission';
                   8243: 	}
                   8244: 	formname.command.value = cmd;
                   8245: 	if (val < 5) formname.submit();
                   8246: 	if (val == 5) {
1.458     banghart 8247: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8248: 	        return false;
                   8249: 	    } else {
                   8250: 	        formname.submit();
                   8251: 	    }
1.445     banghart 8252: 	}
                   8253:     }
1.443     banghart 8254: 
                   8255:     function checkReceiptNo(formname,nospace) {
                   8256: 	var receiptNo = formname.receipt.value;
                   8257: 	var checkOpt = false;
                   8258: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8259: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8260: 	if (checkOpt) {
                   8261: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   8262: 	    formname.receipt.value = "";
                   8263: 	    formname.receipt.focus();
                   8264: 	    return false;
                   8265: 	}
                   8266: 	return true;
                   8267:     }
                   8268: </script>
                   8269: GRADINGMENUJS
                   8270:     &commonJSfunctions($request);
                   8271:     return $Str;    
                   8272: }
                   8273: 
                   8274: 
                   8275: #--- Displays the submissions first page -------
                   8276: sub submit_options {
1.72      ng       8277:     my ($request) = @_;
1.324     albertel 8278:     my ($symb)=&get_symb($request);
1.72      ng       8279:     if (!$symb) {return '';}
1.76      ng       8280:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8281: 
                   8282:     $request->print(<<GRADINGMENUJS);
                   8283: <script type="text/javascript" language="javascript">
1.116     ng       8284:     function checkChoice(formname,val,cmdx) {
                   8285: 	if (val <= 2) {
                   8286: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8287: 	    var cmdsave = cmd;
1.116     ng       8288: 	} else {
                   8289: 	    cmd = cmdx;
1.118     ng       8290: 	    cmdsave = 'submission';
1.116     ng       8291: 	}
                   8292: 	formname.command.value = cmd;
1.118     ng       8293: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8294: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8295: 	if (val < 5) formname.submit();
                   8296: 	if (val == 5) {
1.72      ng       8297: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8298: 	    formname.submit();
                   8299: 	}
1.238     albertel 8300: 	if (val < 7) formname.submit();
1.72      ng       8301:     }
                   8302: 
                   8303:     function checkReceiptNo(formname,nospace) {
                   8304: 	var receiptNo = formname.receipt.value;
                   8305: 	var checkOpt = false;
                   8306: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8307: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8308: 	if (checkOpt) {
                   8309: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   8310: 	    formname.receipt.value = "";
                   8311: 	    formname.receipt.focus();
                   8312: 	    return false;
                   8313: 	}
                   8314: 	return true;
                   8315:     }
                   8316: </script>
                   8317: GRADINGMENUJS
1.118     ng       8318:     &commonJSfunctions($request);
1.324     albertel 8319:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8320:     my $result;
1.76      ng       8321:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8322:     my $savedState = &savedState();
1.118     ng       8323:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8324:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8325:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8326:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8327: 
                   8328:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8329: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8330: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8331: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8332: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8333: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8334: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8335: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8336: 
1.472     albertel 8337:     $result.='
                   8338:     <div class="LC_grade_select_mode">
1.473     albertel 8339:       <div class="LC_grade_select_mode_current">
                   8340:         <h2>
                   8341:           '.&mt('Grade Current Resource').'
                   8342:         </h2>
                   8343:         <div class="LC_grade_select_mode_body">
                   8344:           <div class="LC_grades_resource_info">
                   8345:            '.$table.'
                   8346:           </div>
                   8347:           <div class="LC_grade_select_mode_selector">
                   8348:              <div class="LC_grade_select_mode_selector_header">
                   8349:                 '.&mt('Sections').'
                   8350:              </div>
                   8351:              <div class="LC_grade_select_mode_selector_body">
                   8352: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       8353:     if (ref($sections)) {
1.524     raeburn  8354: 	foreach my $section (sort(@$sections)) {
1.472     albertel 8355: 	    $result.='<option value="'.$section.'" '.
                   8356: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 8357: 	}
1.116     ng       8358:     }
1.401     albertel 8359:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8360:     $result.='
1.473     albertel 8361:              </div>
                   8362:           </div>
                   8363:           <div class="LC_grade_select_mode_selector">
                   8364:              <div class="LC_grade_select_mode_selector_header">
                   8365:                 '.&mt('Groups').'
                   8366:              </div>
                   8367:              <div class="LC_grade_select_mode_selector_body">
                   8368:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8369:              </div>
1.472     albertel 8370:           </div>
1.473     albertel 8371:           <div class="LC_grade_select_mode_selector">
                   8372:              <div class="LC_grade_select_mode_selector_header">
                   8373:                 '.&mt('Access Status').'
                   8374:              </div>
                   8375:              <div class="LC_grade_select_mode_selector_body">
                   8376:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8377:              </div>
1.472     albertel 8378:           </div>
1.473     albertel 8379:           <div class="LC_grade_select_mode_selector">
                   8380:              <div class="LC_grade_select_mode_selector_header">
                   8381:                 '.&mt('Submission Status').'
                   8382:              </div>
                   8383:              <div class="LC_grade_select_mode_selector_body">
                   8384:                <select name="submitonly" size="5">
                   8385: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8386: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8387: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8388: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8389:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   8390:                </select>
                   8391:              </div>
1.472     albertel 8392:           </div>
1.473     albertel 8393:           <div class="LC_grade_select_mode_type_body">
                   8394:             <div class="LC_grade_select_mode_type">
                   8395:               <label>
                   8396:                 <input type="radio" name="radioChoice" value="submission" '.
                   8397:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8398:              &mt('Select individual students to grade and view submissions.').'
                   8399: 	      </label> 
                   8400:             </div>
                   8401:             <div class="LC_grade_select_mode_type">
                   8402: 	      <label>
                   8403:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8404:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8405:                     &mt('Grade all selected students in a grading table.').'
                   8406:               </label>
                   8407:             </div>
                   8408:             <div class="LC_grade_select_mode_type">
                   8409: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   8410:             </div>
1.472     albertel 8411:           </div>
1.473     albertel 8412:         </div>
                   8413:       </div>
                   8414:       <div class="LC_grade_select_mode_page">
                   8415:         <h2>
                   8416:          '.&mt('Grade Complete Folder for One Student').'
                   8417:         </h2>
                   8418:         <div class="LC_grades_select_mode_body">
                   8419:           <div class="LC_grade_select_mode_type_body">
                   8420:             <div class="LC_grade_select_mode_type">
                   8421:               <label>
                   8422:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8423: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8424:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8425:               </label>
                   8426:             </div>
                   8427:             <div class="LC_grade_select_mode_type">
                   8428: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   8429:             </div>
1.472     albertel 8430:           </div>
                   8431:         </div>
                   8432:       </div>
                   8433:     </div>
                   8434:   </form>';
1.499     albertel 8435:     $result .= &show_grading_menu_form($symb);
1.44      ng       8436:     return $result;
1.2       albertel 8437: }
                   8438: 
1.285     albertel 8439: sub reset_perm {
                   8440:     undef(%perm);
                   8441: }
                   8442: 
                   8443: sub init_perm {
                   8444:     &reset_perm();
1.300     albertel 8445:     foreach my $test_perm ('vgr','mgr','opa') {
                   8446: 
                   8447: 	my $scope = $env{'request.course.id'};
                   8448: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8449: 
                   8450: 	    $scope .= '/'.$env{'request.course.sec'};
                   8451: 	    if ( $perm{$test_perm}=
                   8452: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8453: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8454: 	    } else {
                   8455: 		delete($perm{$test_perm});
                   8456: 	    }
1.285     albertel 8457: 	}
                   8458:     }
                   8459: }
                   8460: 
1.400     www      8461: sub gather_clicker_ids {
1.408     albertel 8462:     my %clicker_ids;
1.400     www      8463: 
                   8464:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8465: 
                   8466:     # Set up a couple variables.
1.407     albertel 8467:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8468:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8469:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8470: 
1.407     albertel 8471:     foreach my $student (keys(%$classlist)) {
1.438     www      8472:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8473:         my $username = $classlist->{$student}->[$username_idx];
                   8474:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8475:         my $clickers =
1.408     albertel 8476: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8477:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8478:             $id=~s/^[\#0]+//;
1.421     www      8479:             $id=~s/[\-\:]//g;
1.407     albertel 8480:             if (exists($clicker_ids{$id})) {
1.408     albertel 8481: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8482:             } else {
1.408     albertel 8483: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8484:             }
                   8485:         }
                   8486:     }
1.407     albertel 8487:     return %clicker_ids;
1.400     www      8488: }
                   8489: 
1.402     www      8490: sub gather_adv_clicker_ids {
1.408     albertel 8491:     my %clicker_ids;
1.402     www      8492:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8493:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8494:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8495:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8496:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8497:             my ($puname,$pudom)=split(/\:/,$person);
                   8498:             my $clickers =
1.408     albertel 8499: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8500:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8501: 		$id=~s/^[\#0]+//;
1.421     www      8502:                 $id=~s/[\-\:]//g;
1.408     albertel 8503: 		if (exists($clicker_ids{$id})) {
                   8504: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8505: 		} else {
                   8506: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8507: 		}
1.405     www      8508:             }
1.402     www      8509:         }
                   8510:     }
1.407     albertel 8511:     return %clicker_ids;
1.402     www      8512: }
                   8513: 
1.413     www      8514: sub clicker_grading_parameters {
                   8515:     return ('gradingmechanism' => 'scalar',
                   8516:             'upfiletype' => 'scalar',
                   8517:             'specificid' => 'scalar',
                   8518:             'pcorrect' => 'scalar',
                   8519:             'pincorrect' => 'scalar');
                   8520: }
                   8521: 
1.400     www      8522: sub process_clicker {
                   8523:     my ($r)=@_;
                   8524:     my ($symb)=&get_symb($r);
                   8525:     if (!$symb) {return '';}
                   8526:     my $result=&checkforfile_js();
                   8527:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8528:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8529:     $result.=$table;
                   8530:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8531:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   8532:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   8533:         '.</b></td></tr>'."\n";
                   8534:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8535: # Attempt to restore parameters from last session, set defaults if not present
                   8536:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8537:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8538:                                                  \%Saveable_Parameters);
                   8539:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8540:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8541:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8542:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8543: 
                   8544:     my %checked;
1.521     www      8545:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8546:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   8547:           $checked{$gradingmechanism}="checked='checked'";
                   8548:        }
                   8549:     }
                   8550: 
1.400     www      8551:     my $upload=&mt("Upload File");
                   8552:     my $type=&mt("Type");
1.402     www      8553:     my $attendance=&mt("Award points just for participation");
                   8554:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8555:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8556:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8557:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8558:     my $pcorrect=&mt("Percentage points for correct solution");
                   8559:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8560:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8561: 						   ('iclicker' => 'i>clicker',
                   8562:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8563:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8564:     $result.=<<ENDUPFORM;
1.402     www      8565: <script type="text/javascript">
                   8566: function sanitycheck() {
                   8567: // Accept only integer percentages
                   8568:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8569:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8570: // Find out grading choice
                   8571:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8572:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8573:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8574:       }
                   8575:    }
                   8576: // By default, new choice equals user selection
                   8577:    newgradingchoice=gradingchoice;
                   8578: // Not good to give more points for false answers than correct ones
                   8579:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8580:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8581:    }
                   8582: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8583:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8584:       document.forms.gradesupload.pcorrect.value=100;
                   8585:       document.forms.gradesupload.pincorrect.value=100;
                   8586:    }
                   8587: // If the values are different, cannot be attendance only
                   8588:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8589:        (gradingchoice=='attendance')) {
                   8590:        newgradingchoice='personnel';
                   8591:    }
                   8592: // Change grading choice to new one
                   8593:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8594:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8595:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8596:       } else {
                   8597:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8598:       }
                   8599:    }
                   8600: // Remember the old state
                   8601:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8602: }
                   8603: </script>
1.400     www      8604: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8605: <input type="hidden" name="symb" value="$symb" />
                   8606: <input type="hidden" name="command" value="processclickerfile" />
                   8607: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8608: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8609: <input type="file" name="upfile" size="50" />
                   8610: <br /><label>$type: $selectform</label>
1.451     albertel 8611: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8612: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8613: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8614: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.521     www      8615: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
                   8616: <br />&nbsp;&nbsp;&nbsp;
                   8617: <input type="text" name="givenanswer" size="50" />
1.413     www      8618: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8619: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8620: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8621: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8622: </form>
                   8623: ENDUPFORM
                   8624:     $result.='</td></tr></table>'."\n".
                   8625:              '</td></tr></table><br /><br />'."\n";
                   8626:     $result.=&show_grading_menu_form($symb);
                   8627:     return $result;
                   8628: }
                   8629: 
                   8630: sub process_clicker_file {
                   8631:     my ($r)=@_;
                   8632:     my ($symb)=&get_symb($r);
                   8633:     if (!$symb) {return '';}
1.413     www      8634: 
                   8635:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8636:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8637:                                               \%Saveable_Parameters);
                   8638: 
1.400     www      8639:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8640:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8641: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8642: 	return $result.&show_grading_menu_form($symb);
1.404     www      8643:     }
1.522     www      8644:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8645:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8646:         return $result.&show_grading_menu_form($symb);
                   8647:     }
1.522     www      8648:     my $foundgiven=0;
1.521     www      8649:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8650:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8651:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8652:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8653:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8654:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8655:         $foundgiven=$#answers+1;
1.521     www      8656:     }
1.407     albertel 8657:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8658:     my %correct_ids;
1.404     www      8659:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8660: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8661:     }
                   8662:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8663: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8664: 	   $correct_id=~tr/a-z/A-Z/;
                   8665: 	   $correct_id=~s/\s//gs;
                   8666: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8667:            $correct_id=~s/[\-\:]//g;
1.414     www      8668:            if ($correct_id) {
                   8669: 	      $correct_ids{$correct_id}='specified';
                   8670:            }
                   8671:         }
1.400     www      8672:     }
1.404     www      8673:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8674: 	$result.=&mt('Score based on attendance only');
1.521     www      8675:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8676:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8677:     } else {
1.408     albertel 8678: 	my $number=0;
1.411     www      8679: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8680: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8681: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8682: 	    if ($correct_ids{$id} eq 'specified') {
                   8683: 		$result.=&mt('specified');
                   8684: 	    } else {
                   8685: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8686: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8687: 	    }
                   8688: 	    $number++;
                   8689: 	}
1.411     www      8690:         $result.="</p>\n";
1.408     albertel 8691: 	if ($number==0) {
                   8692: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8693: 	    return $result.&show_grading_menu_form($symb);
                   8694: 	}
1.404     www      8695:     }
1.405     www      8696:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8697:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8698: 		     '<span class="LC_error">',
                   8699: 		     '</span>',
                   8700: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8701:         return $result.&show_grading_menu_form($symb);
                   8702:     }
1.410     www      8703: 
                   8704: # Were able to get all the info needed, now analyze the file
                   8705: 
1.411     www      8706:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8707:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8708:     my $heading=&mt('Scanning clicker file');
                   8709:     $result.=(<<ENDHEADER);
                   8710: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8711: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8712: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8713: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8714: <input type="hidden" name="symb" value="$symb" />
                   8715: <input type="hidden" name="command" value="assignclickergrades" />
                   8716: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8717: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8718: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8719: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8720: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8721: ENDHEADER
1.522     www      8722:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8723:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8724:     } 
1.408     albertel 8725:     my %responses;
                   8726:     my @questiontitles;
1.405     www      8727:     my $errormsg='';
                   8728:     my $number=0;
                   8729:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8730: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8731:     }
1.419     www      8732:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8733:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8734:     }
1.411     www      8735:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8736:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8737:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8738:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8739:              '<br />';
1.522     www      8740:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8741:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8742:        return $result.&show_grading_menu_form($symb);
                   8743:     } 
1.414     www      8744: # Remember Question Titles
                   8745: # FIXME: Possibly need delimiter other than ":"
                   8746:     for (my $i=0;$i<$number;$i++) {
                   8747:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8748:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8749:     }
1.411     www      8750:     my $correct_count=0;
                   8751:     my $student_count=0;
                   8752:     my $unknown_count=0;
1.414     www      8753: # Match answers with usernames
                   8754: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8755:     foreach my $id (keys(%responses)) {
1.410     www      8756:        if ($correct_ids{$id}) {
1.414     www      8757:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8758:           $correct_count++;
1.410     www      8759:        } elsif ($clicker_ids{$id}) {
1.437     www      8760:           if ($clicker_ids{$id}=~/\,/) {
                   8761: # More than one user with the same clicker!
                   8762:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8763:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8764:                            "<select name='multi".$id."'>";
                   8765:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8766:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8767:              }
                   8768:              $result.='</select>';
                   8769:              $unknown_count++;
                   8770:           } else {
                   8771: # Good: found one and only one user with the right clicker
                   8772:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8773:              $student_count++;
                   8774:           }
1.410     www      8775:        } else {
1.411     www      8776:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8777:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8778:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8779:                    "\n".&mt("Domain").": ".
                   8780:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8781:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8782:           $unknown_count++;
1.410     www      8783:        }
1.405     www      8784:     }
1.412     www      8785:     $result.='<hr />'.
                   8786:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8787:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8788:        if ($correct_count==0) {
                   8789:           $errormsg.="Found no correct answers answers for grading!";
                   8790:        } elsif ($correct_count>1) {
1.414     www      8791:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8792:        }
                   8793:     }
1.428     www      8794:     if ($number<1) {
                   8795:        $errormsg.="Found no questions.";
                   8796:     }
1.412     www      8797:     if ($errormsg) {
                   8798:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8799:     } else {
                   8800:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8801:     }
                   8802:     $result.='</form></td></tr></table>'."\n".
1.410     www      8803:              '</td></tr></table><br /><br />'."\n";
1.404     www      8804:     return $result.&show_grading_menu_form($symb);
1.400     www      8805: }
                   8806: 
1.405     www      8807: sub iclicker_eval {
1.406     www      8808:     my ($questiontitles,$responses)=@_;
1.405     www      8809:     my $number=0;
                   8810:     my $errormsg='';
                   8811:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8812:         my %components=&Apache::loncommon::record_sep($line);
                   8813:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8814: 	if ($entries[0] eq 'Question') {
                   8815: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8816: 		$$questiontitles[$number]=$entries[$i];
                   8817: 		$number++;
                   8818: 	    }
                   8819: 	}
                   8820: 	if ($entries[0]=~/^\#/) {
                   8821: 	    my $id=$entries[0];
                   8822: 	    my @idresponses;
                   8823: 	    $id=~s/^[\#0]+//;
                   8824: 	    for (my $i=0;$i<$number;$i++) {
                   8825: 		my $idx=3+$i*6;
                   8826: 		push(@idresponses,$entries[$idx]);
                   8827: 	    }
                   8828: 	    $$responses{$id}=join(',',@idresponses);
                   8829: 	}
1.405     www      8830:     }
                   8831:     return ($errormsg,$number);
                   8832: }
                   8833: 
1.419     www      8834: sub interwrite_eval {
                   8835:     my ($questiontitles,$responses)=@_;
                   8836:     my $number=0;
                   8837:     my $errormsg='';
1.420     www      8838:     my $skipline=1;
                   8839:     my $questionnumber=0;
                   8840:     my %idresponses=();
1.419     www      8841:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8842:         my %components=&Apache::loncommon::record_sep($line);
                   8843:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8844:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8845:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8846:         next if $skipline;
                   8847:         if ($entries[0]!=$questionnumber) {
                   8848:            $questionnumber=$entries[0];
                   8849:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8850:            $number++;
1.419     www      8851:         }
1.420     www      8852:         my $id=$entries[4];
                   8853:         $id=~s/^[\#0]+//;
1.421     www      8854:         $id=~s/^v\d*\://i;
                   8855:         $id=~s/[\-\:]//g;
1.420     www      8856:         $idresponses{$id}[$number]=$entries[6];
                   8857:     }
1.524     raeburn  8858:     foreach my $id (keys(%idresponses)) {
1.420     www      8859:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8860:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8861:     }
                   8862:     return ($errormsg,$number);
                   8863: }
                   8864: 
1.414     www      8865: sub assign_clicker_grades {
                   8866:     my ($r)=@_;
                   8867:     my ($symb)=&get_symb($r);
                   8868:     if (!$symb) {return '';}
1.416     www      8869: # See which part we are saving to
                   8870:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8871: # FIXME: This should probably look for the first handgradeable part
                   8872:     my $part=$$partlist[0];
                   8873: # Start screen output
1.414     www      8874:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8875: 
1.414     www      8876:     my $heading=&mt('Assigning grades based on clicker file');
                   8877:     $result.=(<<ENDHEADER);
                   8878: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8879: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8880: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8881: ENDHEADER
                   8882: # Get correct result
                   8883: # FIXME: Possibly need delimiter other than ":"
                   8884:     my @correct=();
1.415     www      8885:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8886:     my $number=$env{'form.number'};
                   8887:     if ($gradingmechanism ne 'attendance') {
1.414     www      8888:        foreach my $key (keys(%env)) {
                   8889:           if ($key=~/^form\.correct\:/) {
                   8890:              my @input=split(/\,/,$env{$key});
                   8891:              for (my $i=0;$i<=$#input;$i++) {
                   8892:                  if (($correct[$i]) && ($input[$i]) &&
                   8893:                      ($correct[$i] ne $input[$i])) {
                   8894:                     $result.='<br /><span class="LC_warning">'.
                   8895:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8896:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8897:                  } elsif ($input[$i]) {
                   8898:                     $correct[$i]=$input[$i];
                   8899:                  }
                   8900:              }
                   8901:           }
                   8902:        }
1.415     www      8903:        for (my $i=0;$i<$number;$i++) {
1.414     www      8904:           if (!$correct[$i]) {
                   8905:              $result.='<br /><span class="LC_error">'.
                   8906:                       &mt('No correct result given for question "[_1]"!',
                   8907:                           $env{'form.question:'.$i}).'</span>';
                   8908:           }
                   8909:        }
                   8910:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8911:     }
                   8912: # Start grading
1.415     www      8913:     my $pcorrect=$env{'form.pcorrect'};
                   8914:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8915:     my $storecount=0;
1.415     www      8916:     foreach my $key (keys(%env)) {
1.420     www      8917:        my $user='';
1.415     www      8918:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8919:           $user=$1;
                   8920:        }
                   8921:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8922:           my $id=$1;
                   8923:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8924:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8925:           } elsif ($env{'form.multi'.$id}) {
                   8926:              $user=$env{'form.multi'.$id};
1.420     www      8927:           }
                   8928:        }
                   8929:        if ($user) { 
1.415     www      8930:           my @answer=split(/\,/,$env{$key});
                   8931:           my $sum=0;
1.522     www      8932:           my $realnumber=$number;
1.415     www      8933:           for (my $i=0;$i<$number;$i++) {
                   8934:              if ($answer[$i]) {
                   8935:                 if ($gradingmechanism eq 'attendance') {
                   8936:                    $sum+=$pcorrect;
1.522     www      8937:                 } elsif ($answer[$i] eq '*') {
                   8938:                    $sum+=$pcorrect;
                   8939:                 } elsif ($answer[$i] eq '-') {
                   8940:                    $realnumber--;
1.415     www      8941:                 } else {
                   8942:                    if ($answer[$i] eq $correct[$i]) {
                   8943:                       $sum+=$pcorrect;
                   8944:                    } else {
                   8945:                       $sum+=$pincorrect;
                   8946:                    }
                   8947:                 }
                   8948:              }
                   8949:           }
1.522     www      8950:           my $ave=$sum/(100*$realnumber);
1.416     www      8951: # Store
                   8952:           my ($username,$domain)=split(/\:/,$user);
                   8953:           my %grades=();
                   8954:           $grades{"resource.$part.solved"}='correct_by_override';
                   8955:           $grades{"resource.$part.awarded"}=$ave;
                   8956:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8957:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8958:                                                  $env{'request.course.id'},
                   8959:                                                  $domain,$username);
                   8960:           if ($returncode ne 'ok') {
                   8961:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8962:           } else {
                   8963:              $storecount++;
                   8964:           }
1.415     www      8965:        }
                   8966:     }
                   8967: # We are done
1.416     www      8968:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8969:              '</td></tr></table>'."\n".
1.414     www      8970:              '</td></tr></table><br /><br />'."\n";
                   8971:     return $result.&show_grading_menu_form($symb);
                   8972: }
                   8973: 
1.1       albertel 8974: sub handler {
1.41      ng       8975:     my $request=$_[0];
1.434     albertel 8976:     &reset_caches();
1.257     albertel 8977:     if ($env{'browser.mathml'}) {
1.141     www      8978: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8979:     } else {
1.141     www      8980: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8981:     }
                   8982:     $request->send_http_header;
1.44      ng       8983:     return '' if $request->header_only;
1.41      ng       8984:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8985:     my $symb=&get_symb($request,1);
1.160     albertel 8986:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8987:     my $command=$commands[0];
1.447     foxr     8988: 
1.160     albertel 8989:     if ($#commands > 0) {
                   8990: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8991:     }
1.447     foxr     8992: 
1.513     foxr     8993:     $ssi_error = 0;
1.353     albertel 8994:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8995:     if ($symb eq '' && $command eq '') {
1.257     albertel 8996: 	if ($env{'user.adv'}) {
                   8997: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8998: 		($env{'form.codethree'})) {
                   8999: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9000: 		    $env{'form.codethree'};
1.41      ng       9001: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9002: 		    &Apache::lonnet::checkin($token);
                   9003: 		if ($tsymb) {
1.137     albertel 9004: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9005: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9006: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9007: 					  ('grade_username' => $tuname,
                   9008: 					   'grade_domain' => $tudom,
                   9009: 					   'grade_courseid' => $tcrsid,
                   9010: 					   'grade_symb' => $tsymb)));
1.41      ng       9011: 		    } else {
1.45      ng       9012: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9013: 		    }
1.41      ng       9014: 		} else {
1.45      ng       9015: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9016: 		}
1.14      www      9017: 	    } else {
1.41      ng       9018: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9019: 	    }
                   9020: 	}
                   9021:     } else {
1.285     albertel 9022: 	&init_perm();
1.104     albertel 9023: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9024: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9025: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9026: 	    &pickStudentPage($request);
1.103     albertel 9027: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9028: 	    &displayPage($request);
1.104     albertel 9029: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9030: 	    &updateGradeByPage($request);
1.104     albertel 9031: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9032: 	    &processGroup($request);
1.104     albertel 9033: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9034: 	    $request->print(&grading_menu($request));
                   9035: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9036: 	    $request->print(&submit_options($request));
1.104     albertel 9037: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9038: 	    $request->print(&viewgrades($request));
1.104     albertel 9039: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9040: 	    $request->print(&processHandGrade($request));
1.106     albertel 9041: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9042: 	    $request->print(&editgrades($request));
1.106     albertel 9043: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9044: 	    $request->print(&verifyreceipt($request));
1.400     www      9045:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9046:             $request->print(&process_clicker($request));
                   9047:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9048:             $request->print(&process_clicker_file($request));
1.414     www      9049:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9050:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9051: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9052: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9053: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9054: 	    $request->print(&csvupload($request));
1.106     albertel 9055: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9056: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9057: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9058: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9059: 		$request->print(&csvuploadoptions($request));
1.41      ng       9060: 	    } else {
1.257     albertel 9061: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9062: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9063: 		} else {
1.257     albertel 9064: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9065: 		}
                   9066: 		$request->print(&csvuploadmap($request));
                   9067: 	    }
1.246     albertel 9068: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9069: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9070: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9071: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9072:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9073:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9074: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9075: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9076: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9077: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9078:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9079:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9080: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9081:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9082:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9083:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9084: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9085:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9086:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9087: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9088:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9089:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9090:             $request->print(&checkscantron_results($request));     
1.106     albertel 9091: 	} elsif ($command) {
1.157     albertel 9092: 	    $request->print("Access Denied ($command)");
1.26      albertel 9093: 	}
1.2       albertel 9094:     }
1.513     foxr     9095:     if ($ssi_error) {
                   9096: 	&ssi_print_error($request);
                   9097:     }
1.353     albertel 9098:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9099:     &reset_caches();
1.44      ng       9100:     return '';
                   9101: }
                   9102: 
1.1       albertel 9103: 1;
                   9104: 
1.13      albertel 9105: __END__;

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