File:
[LON-CAPA] /
loncom /
homework /
grades.pm
Revision
1.654:
download - view:
text,
annotated -
select for diffs
Sat Oct 1 15:55:51 2011 UTC (12 years, 10 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Handback of multiple files to one student.
- Streamline process (one message for all returned files for a problem).
- Localize message text according to recipient's language.
- More robust if multiple file uploads by student for a single response:
- Handback files will be uploaded and message sent for each and all
files returned by the instructor.
1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.654 2011/10/01 15:55:51 raeburn Exp $
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: #
28:
29:
30:
31: package Apache::grades;
32: use strict;
33: use Apache::style;
34: use Apache::lonxml;
35: use Apache::lonnet;
36: use Apache::loncommon;
37: use Apache::lonhtmlcommon;
38: use Apache::lonnavmaps;
39: use Apache::lonhomework;
40: use Apache::lonpickcode;
41: use Apache::loncoursedata;
42: use Apache::lonmsg();
43: use Apache::Constants qw(:common :http);
44: use Apache::lonlocal;
45: use Apache::lonenc;
46: use Apache::lonstathelpers;
47: use Apache::lonquickgrades;
48: use String::Similarity;
49: use LONCAPA;
50:
51: use POSIX qw(floor);
52:
53:
54:
55: my %perm=();
56:
57: # These variables are used to recover from ssi errors
58:
59: my $ssi_retries = 5;
60: my $ssi_error;
61: my $ssi_error_resource;
62: my $ssi_error_message;
63:
64:
65: sub ssi_with_retries {
66: my ($resource, $retries, %form) = @_;
67: my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
68: if ($response->is_error) {
69: $ssi_error = 1;
70: $ssi_error_resource = $resource;
71: $ssi_error_message = $response->code . " " . $response->message;
72: }
73:
74: return $content;
75:
76: }
77: #
78: # Prodcuces an ssi retry failure error message to the user:
79: #
80:
81: sub ssi_print_error {
82: my ($r) = @_;
83: my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
84: $r->print('
85: <br />
86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
87: <p>
88: '.&mt('Unable to retrieve a resource from a server:').'<br />
89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
90: '.&mt('Error:').' '.$ssi_error_message.'
91: </p>
92: <p>'.
93: &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 />'.
94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
95: '</p>');
96: return;
97: }
98:
99: #
100: # --- Retrieve the parts from the metadata file.---
101: # Returns an array of everything that the resources stores away
102: #
103:
104: sub getpartlist {
105: my ($symb,$errorref) = @_;
106:
107: my $navmap = Apache::lonnavmaps::navmap->new();
108: unless (ref($navmap)) {
109: if (ref($errorref)) {
110: $$errorref = 'navmap';
111: return;
112: }
113: }
114: my $res = $navmap->getBySymb($symb);
115: my $partlist = $res->parts();
116: my $url = $res->src();
117: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
118:
119: my @stores;
120: foreach my $part (@{ $partlist }) {
121: foreach my $key (@metakeys) {
122: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
123: }
124: }
125: return @stores;
126: }
127:
128: #--- Format fullname, username:domain if different for display
129: #--- Use anywhere where the student names are listed
130: sub nameUserString {
131: my ($type,$fullname,$uname,$udom) = @_;
132: if ($type eq 'header') {
133: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
134: } else {
135: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
136: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
137: }
138: }
139:
140: #--- Get the partlist and the response type for a given problem. ---
141: #--- Indicate if a response type is coded handgraded or not. ---
142: #--- Sets response_error pointer to "1" if navmaps object broken ---
143: sub response_type {
144: my ($symb,$response_error) = @_;
145:
146: my $navmap = Apache::lonnavmaps::navmap->new();
147: unless (ref($navmap)) {
148: if (ref($response_error)) {
149: $$response_error = 1;
150: }
151: return;
152: }
153: my $res = $navmap->getBySymb($symb);
154: unless (ref($res)) {
155: $$response_error = 1;
156: return;
157: }
158: my $partlist = $res->parts();
159: my %vPart =
160: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
161: my (%response_types,%handgrade);
162: foreach my $part (@{ $partlist }) {
163: next if (%vPart && !exists($vPart{$part}));
164:
165: my @types = $res->responseType($part);
166: my @ids = $res->responseIds($part);
167: for (my $i=0; $i < scalar(@ids); $i++) {
168: $response_types{$part}{$ids[$i]} = $types[$i];
169: $handgrade{$part.'_'.$ids[$i]} =
170: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
171: '.handgrade',$symb);
172: }
173: }
174: return ($partlist,\%handgrade,\%response_types);
175: }
176:
177: sub flatten_responseType {
178: my ($responseType) = @_;
179: my @part_response_id =
180: map {
181: my $part = $_;
182: map {
183: [$part,$_]
184: } sort(keys(%{ $responseType->{$part} }));
185: } sort(keys(%$responseType));
186: return @part_response_id;
187: }
188:
189: sub get_display_part {
190: my ($partID,$symb)=@_;
191: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
192: if (defined($display) and $display ne '') {
193: $display.= ' (<span class="LC_internal_info">'
194: .&mt('Part ID: [_1]',$partID).'</span>)';
195: } else {
196: $display=$partID;
197: }
198: return $display;
199: }
200:
201: sub reset_caches {
202: &reset_analyze_cache();
203: &reset_perm();
204: }
205:
206: {
207: my %analyze_cache;
208: my %analyze_cache_formkeys;
209:
210: sub reset_analyze_cache {
211: undef(%analyze_cache);
212: undef(%analyze_cache_formkeys);
213: }
214:
215: sub get_analyze {
216: my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
217: my $key = "$symb\0$uname\0$udom";
218: if ($type eq 'randomizetry') {
219: if ($trial ne '') {
220: $key .= "\0".$trial;
221: }
222: }
223: if (exists($analyze_cache{$key})) {
224: my $getupdate = 0;
225: if (ref($add_to_hash) eq 'HASH') {
226: foreach my $item (keys(%{$add_to_hash})) {
227: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
228: if (!exists($analyze_cache_formkeys{$key}{$item})) {
229: $getupdate = 1;
230: last;
231: }
232: } else {
233: $getupdate = 1;
234: }
235: }
236: }
237: if (!$getupdate) {
238: return $analyze_cache{$key};
239: }
240: }
241:
242: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
243: $url=&Apache::lonnet::clutter($url);
244: my %form = ('grade_target' => 'analyze',
245: 'grade_domain' => $udom,
246: 'grade_symb' => $symb,
247: 'grade_courseid' => $env{'request.course.id'},
248: 'grade_username' => $uname,
249: 'grade_noincrement' => $no_increment);
250: if ($bubbles_per_row ne '') {
251: $form{'bubbles_per_row'} = $bubbles_per_row;
252: }
253: if ($type eq 'randomizetry') {
254: $form{'grade_questiontype'} = $type;
255: if ($rndseed ne '') {
256: $form{'grade_rndseed'} = $rndseed;
257: }
258: }
259: if (ref($add_to_hash)) {
260: %form = (%form,%{$add_to_hash});
261: }
262: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
263: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
264: my %analyze=&Apache::lonnet::str2hash($subresult);
265: if (ref($add_to_hash) eq 'HASH') {
266: $analyze_cache_formkeys{$key} = $add_to_hash;
267: } else {
268: $analyze_cache_formkeys{$key} = {};
269: }
270: return $analyze_cache{$key} = \%analyze;
271: }
272:
273: sub get_order {
274: my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
275: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
276: return $analyze->{"$partid.$respid.shown"};
277: }
278:
279: sub get_radiobutton_correct_foil {
280: my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
281: my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
282: my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
283: if (ref($foils) eq 'ARRAY') {
284: foreach my $foil (@{$foils}) {
285: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
286: return $foil;
287: }
288: }
289: }
290: }
291:
292: sub scantron_partids_tograde {
293: my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
294: my (%analysis,@parts);
295: if (ref($resource)) {
296: my $symb = $resource->symb();
297: my $add_to_form;
298: if ($check_for_randomlist) {
299: $add_to_form = { 'check_parts_withrandomlist' => 1,};
300: }
301: my $analyze =
302: &get_analyze($symb,$uname,$udom,undef,$add_to_form,
303: undef,undef,undef,$bubbles_per_row);
304: if (ref($analyze) eq 'HASH') {
305: %analysis = %{$analyze};
306: }
307: if (ref($analysis{'parts'}) eq 'ARRAY') {
308: foreach my $part (@{$analysis{'parts'}}) {
309: my ($id,$respid) = split(/\./,$part);
310: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
311: push(@parts,$part);
312: }
313: }
314: }
315: }
316: return (\%analysis,\@parts);
317: }
318:
319: }
320:
321: #--- Clean response type for display
322: #--- Currently filters option/rank/radiobutton/match/essay/Task
323: # response types only.
324: sub cleanRecord {
325: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
326: $uname,$udom,$type,$trial,$rndseed) = @_;
327: my $grayFont = '<span class="LC_internal_info">';
328: if ($response =~ /^(option|rank)$/) {
329: my %answer=&Apache::lonnet::str2hash($answer);
330: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
331: my ($toprow,$bottomrow);
332: foreach my $foil (@$order) {
333: if ($grading{$foil} == 1) {
334: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
335: } else {
336: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
337: }
338: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
339: }
340: return '<blockquote><table border="1">'.
341: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
342: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
343: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
344: } elsif ($response eq 'match') {
345: my %answer=&Apache::lonnet::str2hash($answer);
346: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
347: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
348: my ($toprow,$middlerow,$bottomrow);
349: foreach my $foil (@$order) {
350: my $item=shift(@items);
351: if ($grading{$foil} == 1) {
352: $toprow.='<td><b>'.$item.' </b></td>';
353: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
354: } else {
355: $toprow.='<td><i>'.$item.' </i></td>';
356: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
357: }
358: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
359: }
360: return '<blockquote><table border="1">'.
361: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
362: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
363: $middlerow.'</tr>'.
364: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
365: $bottomrow.'</tr>'.'</table></blockquote>';
366: } elsif ($response eq 'radiobutton') {
367: my %answer=&Apache::lonnet::str2hash($answer);
368: my ($toprow,$bottomrow);
369: my $correct =
370: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
371: foreach my $foil (@$order) {
372: if (exists($answer{$foil})) {
373: if ($foil eq $correct) {
374: $toprow.='<td><b>'.&mt('true').'</b></td>';
375: } else {
376: $toprow.='<td><i>'.&mt('true').'</i></td>';
377: }
378: } else {
379: $toprow.='<td>'.&mt('false').'</td>';
380: }
381: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
382: }
383: return '<blockquote><table border="1">'.
384: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
385: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
386: $bottomrow.'</tr>'.'</table></blockquote>';
387: } elsif ($response eq 'essay') {
388: if (! exists ($env{'form.'.$symb})) {
389: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
390: $env{'course.'.$env{'request.course.id'}.'.domain'},
391: $env{'course.'.$env{'request.course.id'}.'.num'});
392:
393: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
394: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
395: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
396: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
397: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
398: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
399: }
400: $answer =~ s-\n-<br />-g;
401: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
402: } elsif ( $response eq 'organic') {
403: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
404: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
405: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
406: return $result;
407: } elsif ( $response eq 'Task') {
408: if ( $answer eq 'SUBMITTED') {
409: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
410: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
411: return $result;
412: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
413: my @matches = grep(/^\Q$version\E.*?\.instance$/,
414: keys(%{$record}));
415: return join('<br />',($version,@matches));
416:
417:
418: } else {
419: my $result =
420: '<p>'
421: .&mt('Overall result: [_1]',
422: $record->{$version."resource.$respid.$partid.status"})
423: .'</p>';
424:
425: $result .= '<ul>';
426: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
427: keys(%{$record}));
428: foreach my $grade (sort(@grade)) {
429: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
430: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
431: $dim, $record->{$grade}).
432: '</li>';
433: }
434: $result.='</ul>';
435: return $result;
436: }
437: } elsif ( $response =~ m/(?:numerical|formula)/) {
438: $answer =
439: &Apache::loncommon::format_previous_attempt_value('submission',
440: $answer);
441: }
442: return $answer;
443: }
444:
445: #-- A couple of common js functions
446: sub commonJSfunctions {
447: my $request = shift;
448: $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
449: function radioSelection(radioButton) {
450: var selection=null;
451: if (radioButton.length > 1) {
452: for (var i=0; i<radioButton.length; i++) {
453: if (radioButton[i].checked) {
454: return radioButton[i].value;
455: }
456: }
457: } else {
458: if (radioButton.checked) return radioButton.value;
459: }
460: return selection;
461: }
462:
463: function pullDownSelection(selectOne) {
464: var selection="";
465: if (selectOne.length > 1) {
466: for (var i=0; i<selectOne.length; i++) {
467: if (selectOne[i].selected) {
468: return selectOne[i].value;
469: }
470: }
471: } else {
472: // only one value it must be the selected one
473: return selectOne.value;
474: }
475: }
476: COMMONJSFUNCTIONS
477: }
478:
479: #--- Dumps the class list with usernames,list of sections,
480: #--- section, ids and fullnames for each user.
481: sub getclasslist {
482: my ($getsec,$filterlist,$getgroup) = @_;
483: my @getsec;
484: my @getgroup;
485: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
486: if (!ref($getsec)) {
487: if ($getsec ne '' && $getsec ne 'all') {
488: @getsec=($getsec);
489: }
490: } else {
491: @getsec=@{$getsec};
492: }
493: if (grep(/^all$/,@getsec)) { undef(@getsec); }
494: if (!ref($getgroup)) {
495: if ($getgroup ne '' && $getgroup ne 'all') {
496: @getgroup=($getgroup);
497: }
498: } else {
499: @getgroup=@{$getgroup};
500: }
501: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
502:
503: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
504: # Bail out if we were unable to get the classlist
505: return if (! defined($classlist));
506: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
507: #
508: my %sections;
509: my %fullnames;
510: foreach my $student (keys(%$classlist)) {
511: my $end =
512: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
513: my $start =
514: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
515: my $id =
516: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
517: my $section =
518: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
519: my $fullname =
520: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
521: my $status =
522: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
523: my $group =
524: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
525: # filter students according to status selected
526: if ($filterlist && (!($stu_status =~ /Any/))) {
527: if (!($stu_status =~ $status)) {
528: delete($classlist->{$student});
529: next;
530: }
531: }
532: # filter students according to groups selected
533: my @stu_groups = split(/,/,$group);
534: if (@getgroup) {
535: my $exclude = 1;
536: foreach my $grp (@getgroup) {
537: foreach my $stu_group (@stu_groups) {
538: if ($stu_group eq $grp) {
539: $exclude = 0;
540: }
541: }
542: if (($grp eq 'none') && !$group) {
543: $exclude = 0;
544: }
545: }
546: if ($exclude) {
547: delete($classlist->{$student});
548: }
549: }
550: $section = ($section ne '' ? $section : 'none');
551: if (&canview($section)) {
552: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
553: $sections{$section}++;
554: if ($classlist->{$student}) {
555: $fullnames{$student}=$fullname;
556: }
557: } else {
558: delete($classlist->{$student});
559: }
560: } else {
561: delete($classlist->{$student});
562: }
563: }
564: my %seen = ();
565: my @sections = sort(keys(%sections));
566: return ($classlist,\@sections,\%fullnames);
567: }
568:
569: sub canmodify {
570: my ($sec)=@_;
571: if ($perm{'mgr'}) {
572: if (!defined($perm{'mgr_section'})) {
573: # can modify whole class
574: return 1;
575: } else {
576: if ($sec eq $perm{'mgr_section'}) {
577: #can modify the requested section
578: return 1;
579: } else {
580: # can't modify the request section
581: return 0;
582: }
583: }
584: }
585: #can't modify
586: return 0;
587: }
588:
589: sub canview {
590: my ($sec)=@_;
591: if ($perm{'vgr'}) {
592: if (!defined($perm{'vgr_section'})) {
593: # can modify whole class
594: return 1;
595: } else {
596: if ($sec eq $perm{'vgr_section'}) {
597: #can modify the requested section
598: return 1;
599: } else {
600: # can't modify the request section
601: return 0;
602: }
603: }
604: }
605: #can't modify
606: return 0;
607: }
608:
609: #--- Retrieve the grade status of a student for all the parts
610: sub student_gradeStatus {
611: my ($symb,$udom,$uname,$partlist) = @_;
612: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
613: my %partstatus = ();
614: foreach (@$partlist) {
615: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
616: $status = 'nothing' if ($status eq '');
617: $partstatus{$_} = $status;
618: my $subkey = "resource.$_.submitted_by";
619: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
620: }
621: return %partstatus;
622: }
623:
624: # hidden form and javascript that calls the form
625: # Use by verifyscript and viewgrades
626: # Shows a student's view of problem and submission
627: sub jscriptNform {
628: my ($symb) = @_;
629: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
630: my $jscript= &Apache::lonhtmlcommon::scripttag(
631: ' function viewOneStudent(user,domain) {'."\n".
632: ' document.onestudent.student.value = user;'."\n".
633: ' document.onestudent.userdom.value = domain;'."\n".
634: ' document.onestudent.submit();'."\n".
635: ' }'."\n".
636: "\n");
637: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
638: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
639: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
640: '<input type="hidden" name="command" value="submission" />'."\n".
641: '<input type="hidden" name="student" value="" />'."\n".
642: '<input type="hidden" name="userdom" value="" />'."\n".
643: '</form>'."\n";
644: return $jscript;
645: }
646:
647:
648:
649: # Given the score (as a number [0-1] and the weight) what is the final
650: # point value? This function will round to the nearest tenth, third,
651: # or quarter if one of those is within the tolerance of .00001.
652: sub compute_points {
653: my ($score, $weight) = @_;
654:
655: my $tolerance = .00001;
656: my $points = $score * $weight;
657:
658: # Check for nearness to 1/x.
659: my $check_for_nearness = sub {
660: my ($factor) = @_;
661: my $num = ($points * $factor) + $tolerance;
662: my $floored_num = floor($num);
663: if ($num - $floored_num < 2 * $tolerance * $factor) {
664: return $floored_num / $factor;
665: }
666: return $points;
667: };
668:
669: $points = $check_for_nearness->(10);
670: $points = $check_for_nearness->(3);
671: $points = $check_for_nearness->(4);
672:
673: return $points;
674: }
675:
676: #------------------ End of general use routines --------------------
677:
678: #
679: # Find most similar essay
680: #
681:
682: sub most_similar {
683: my ($uname,$udom,$uessay,$old_essays)=@_;
684:
685: # ignore spaces and punctuation
686:
687: $uessay=~s/\W+/ /gs;
688:
689: # ignore empty submissions (occuring when only files are sent)
690:
691: unless ($uessay=~/\w+/s) { return ''; }
692:
693: # these will be returned. Do not care if not at least 50 percent similar
694: my $limit=0.6;
695: my $sname='';
696: my $sdom='';
697: my $scrsid='';
698: my $sessay='';
699: # go through all essays ...
700: foreach my $tkey (keys(%$old_essays)) {
701: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
702: # ... except the same student
703: next if (($tname eq $uname) && ($tdom eq $udom));
704: my $tessay=$old_essays->{$tkey};
705: $tessay=~s/\W+/ /gs;
706: # String similarity gives up if not even limit
707: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
708: # Found one
709: if ($tsimilar>$limit) {
710: $limit=$tsimilar;
711: $sname=$tname;
712: $sdom=$tdom;
713: $scrsid=$tcrsid;
714: $sessay=$old_essays->{$tkey};
715: }
716: }
717: if ($limit>0.6) {
718: return ($sname,$sdom,$scrsid,$sessay,$limit);
719: } else {
720: return ('','','','',0);
721: }
722: }
723:
724: #-------------------------------------------------------------------
725:
726: #------------------------------------ Receipt Verification Routines
727: #
728:
729: sub initialverifyreceipt {
730: my ($request,$symb) = @_;
731: &commonJSfunctions($request);
732: return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
733: &Apache::lonnet::recprefix($env{'request.course.id'}).
734: '-<input type="text" name="receipt" size="4" />'.
735: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
736: '<input type="hidden" name="command" value="verify" />'.
737: "</form>\n";
738: }
739:
740: #--- Check whether a receipt number is valid.---
741: sub verifyreceipt {
742: my ($request,$symb) = @_;
743:
744: my $courseid = $env{'request.course.id'};
745: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
746: $env{'form.receipt'};
747: $receipt =~ s/[^\-\d]//g;
748:
749: my $title.=
750: '<h3><span class="LC_info">'.
751: &mt('Verifying Receipt Number [_1]',$receipt).
752: '</span></h3>'."\n";
753:
754: my ($string,$contents,$matches) = ('','',0);
755: my (undef,undef,$fullname) = &getclasslist('all','0');
756:
757: my $receiptparts=0;
758: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
759: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
760: my $parts=['0'];
761: if ($receiptparts) {
762: my $res_error;
763: ($parts)=&response_type($symb,\$res_error);
764: if ($res_error) {
765: return &navmap_errormsg();
766: }
767: }
768:
769: my $header =
770: &Apache::loncommon::start_data_table().
771: &Apache::loncommon::start_data_table_header_row().
772: '<th> '.&mt('Fullname').' </th>'."\n".
773: '<th> '.&mt('Username').' </th>'."\n".
774: '<th> '.&mt('Domain').' </th>';
775: if ($receiptparts) {
776: $header.='<th> '.&mt('Problem Part').' </th>';
777: }
778: $header.=
779: &Apache::loncommon::end_data_table_header_row();
780:
781: foreach (sort
782: {
783: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
784: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
785: }
786: return $a cmp $b;
787: } (keys(%$fullname))) {
788: my ($uname,$udom)=split(/\:/);
789: foreach my $part (@$parts) {
790: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
791: $contents.=
792: &Apache::loncommon::start_data_table_row().
793: '<td> '."\n".
794: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
795: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
796: '<td> '.$uname.' </td>'.
797: '<td> '.$udom.' </td>';
798: if ($receiptparts) {
799: $contents.='<td> '.$part.' </td>';
800: }
801: $contents.=
802: &Apache::loncommon::end_data_table_row()."\n";
803:
804: $matches++;
805: }
806: }
807: }
808: if ($matches == 0) {
809: $string = $title
810: .'<p class="LC_warning">'
811: .&mt('No match found for the above receipt number.')
812: .'</p>';
813: } else {
814: $string = &jscriptNform($symb).$title.
815: '<p>'.
816: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
817: '</p>'.
818: $header.
819: $contents.
820: &Apache::loncommon::end_data_table()."\n";
821: }
822: return $string;
823: }
824:
825: #--- This is called by a number of programs.
826: #--- Called from the Grading Menu - View/Grade an individual student
827: #--- Also called directly when one clicks on the subm button
828: # on the problem page.
829: sub listStudents {
830: my ($request,$symb,$submitonly) = @_;
831:
832: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
833: my $cnum = $env{"course.$env{'request.course.id'}.num"};
834: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
835: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
836: unless ($submitonly) {
837: $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
838: }
839:
840: my $result='';
841: my $res_error;
842: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
843:
844: my %lt = &Apache::lonlocal::texthash (
845: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
846: 'single' => 'Please select the student before clicking on the Next button.',
847: );
848: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
849: function checkSelect(checkBox) {
850: var ctr=0;
851: var sense="";
852: if (checkBox.length > 1) {
853: for (var i=0; i<checkBox.length; i++) {
854: if (checkBox[i].checked) {
855: ctr++;
856: }
857: }
858: sense = '$lt{'multiple'}';
859: } else {
860: if (checkBox.checked) {
861: ctr = 1;
862: }
863: sense = '$lt{'single'}';
864: }
865: if (ctr == 0) {
866: alert(sense);
867: return false;
868: }
869: document.gradesub.submit();
870: }
871:
872: function reLoadList(formname) {
873: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
874: formname.command.value = 'submission';
875: formname.submit();
876: }
877: LISTJAVASCRIPT
878:
879: &commonJSfunctions($request);
880: $request->print($result);
881:
882: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
883: "\n";
884:
885: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
886: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
887: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
888: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
889: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
890: .&Apache::lonhtmlcommon::row_closure();
891: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
892: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
893: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
894: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
895: .&Apache::lonhtmlcommon::row_closure();
896:
897: my $submission_options;
898: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
899: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
900: $env{'form.Status'} = $saveStatus;
901: $submission_options.=
902: '<span class="LC_nobreak">'.
903: '<label><input type="radio" name="lastSub" value="lastonly" /> '.
904: &mt('last submission only').' </label></span>'."\n".
905: '<span class="LC_nobreak">'.
906: '<label><input type="radio" name="lastSub" value="last" /> '.
907: &mt('last submission & parts info').' </label></span>'."\n".
908: '<span class="LC_nobreak">'.
909: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
910: &mt('by dates and submissions').'</label></span>'."\n".
911: '<span class="LC_nobreak">'.
912: '<label><input type="radio" name="lastSub" value="all" /> '.
913: &mt('all details').'</label></span>';
914: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
915: .$submission_options
916: .&Apache::lonhtmlcommon::row_closure();
917:
918: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
919: .'<select name="increment">'
920: .'<option value="1">'.&mt('Whole Points').'</option>'
921: .'<option value=".5">'.&mt('Half Points').'</option>'
922: .'<option value=".25">'.&mt('Quarter Points').'</option>'
923: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
924: .'</select>'
925: .&Apache::lonhtmlcommon::row_closure();
926:
927: $gradeTable .=
928: &build_section_inputs().
929: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
930: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
931: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
932:
933: if (exists($env{'form.Status'})) {
934: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
935: } else {
936: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
937: .&Apache::lonhtmlcommon::StatusOptions(
938: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
939: .&Apache::lonhtmlcommon::row_closure();
940: }
941:
942: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
943: .'<input type="checkbox" name="checkPlag" checked="checked" />'
944: .&Apache::lonhtmlcommon::row_closure(1)
945: .&Apache::lonhtmlcommon::end_pick_box();
946:
947: $gradeTable .= '<p>'
948: .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
949: .'<input type="hidden" name="command" value="processGroup" />'
950: .'</p>';
951:
952: # checkall buttons
953: $gradeTable.=&check_script('gradesub', 'stuinfo');
954: $gradeTable.='<input type="button" '."\n".
955: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
956: 'value="'.&mt('Next').' →" /> <br />'."\n";
957: $gradeTable.=&check_buttons();
958: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
959: $gradeTable.= &Apache::loncommon::start_data_table().
960: &Apache::loncommon::start_data_table_header_row();
961: my $loop = 0;
962: while ($loop < 2) {
963: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
964: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
965: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
966: foreach my $part (sort(@$partlist)) {
967: my $display_part=
968: &get_display_part((split(/_/,$part))[0],$symb);
969: $gradeTable.=
970: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
971: }
972: } elsif ($submitonly eq 'queued') {
973: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
974: }
975: $loop++;
976: # $gradeTable.='<td></td>' if ($loop%2 ==1);
977: }
978: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
979:
980: my $ctr = 0;
981: foreach my $student (sort
982: {
983: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
984: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
985: }
986: return $a cmp $b;
987: }
988: (keys(%$fullname))) {
989: my ($uname,$udom) = split(/:/,$student);
990:
991: my %status = ();
992:
993: if ($submitonly eq 'queued') {
994: my %queue_status =
995: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
996: $udom,$uname);
997: next if (!defined($queue_status{'gradingqueue'}));
998: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
999: }
1000:
1001: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1002: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1003: my $submitted = 0;
1004: my $graded = 0;
1005: my $incorrect = 0;
1006: foreach (keys(%status)) {
1007: $submitted = 1 if ($status{$_} ne 'nothing');
1008: $graded = 1 if ($status{$_} =~ /^ungraded/);
1009: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1010:
1011: my ($foo,$partid,$foo1) = split(/\./,$_);
1012: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1013: $submitted = 0;
1014: my ($part)=split(/\./,$partid);
1015: $gradeTable.='<input type="hidden" name="'.
1016: $student.':'.$part.':submitted_by" value="'.
1017: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1018: }
1019: }
1020:
1021: next if (!$submitted && ($submitonly eq 'yes' ||
1022: $submitonly eq 'incorrect' ||
1023: $submitonly eq 'graded'));
1024: next if (!$graded && ($submitonly eq 'graded'));
1025: next if (!$incorrect && $submitonly eq 'incorrect');
1026: }
1027:
1028: $ctr++;
1029: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1030: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1031: if ( $perm{'vgr'} eq 'F' ) {
1032: if ($ctr%2 ==1) {
1033: $gradeTable.= &Apache::loncommon::start_data_table_row();
1034: }
1035: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1036: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1037: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1038: ') " /> </label></td>'."\n".'<td>'.
1039: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1040: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1041:
1042: if ($submitonly ne 'all') {
1043: foreach (sort(keys(%status))) {
1044: next if ($_ =~ /^resource.*?submitted_by$/);
1045: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1046: }
1047: }
1048: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1049: if ($ctr%2 ==0) {
1050: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1051: }
1052: }
1053: }
1054: if ($ctr%2 ==1) {
1055: $gradeTable.='<td> </td><td> </td><td> </td>';
1056: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1057: foreach (@$partlist) {
1058: $gradeTable.='<td> </td>';
1059: }
1060: } elsif ($submitonly eq 'queued') {
1061: $gradeTable.='<td> </td>';
1062: }
1063: $gradeTable.=&Apache::loncommon::end_data_table_row();
1064: }
1065:
1066: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1067: '<input type="button" '.
1068: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1069: 'value="'.&mt('Next').' →" /></form>'."\n";
1070: if ($ctr == 0) {
1071: my $num_students=(scalar(keys(%$fullname)));
1072: if ($num_students eq 0) {
1073: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1074: } else {
1075: my $submissions='submissions';
1076: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1077: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1078: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1079: $gradeTable='<br /> <span class="LC_warning">'.
1080: &mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
1081: $num_students).
1082: '</span><br />';
1083: }
1084: } elsif ($ctr == 1) {
1085: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1086: }
1087: $request->print($gradeTable);
1088: return '';
1089: }
1090:
1091: #---- Called from the listStudents routine
1092:
1093: sub check_script {
1094: my ($form, $type)=@_;
1095: my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1096: function checkall() {
1097: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1098: ele = document.forms.'.$form.'.elements[i];
1099: if (ele.name == "'.$type.'") {
1100: document.forms.'.$form.'.elements[i].checked=true;
1101: }
1102: }
1103: }
1104:
1105: function checksec() {
1106: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1107: ele = document.forms.'.$form.'.elements[i];
1108: string = document.forms.'.$form.'.chksec.value;
1109: if
1110: (ele.value.indexOf(":::SECTION"+string)>0) {
1111: document.forms.'.$form.'.elements[i].checked=true;
1112: }
1113: }
1114: }
1115:
1116:
1117: function uncheckall() {
1118: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1119: ele = document.forms.'.$form.'.elements[i];
1120: if (ele.name == "'.$type.'") {
1121: document.forms.'.$form.'.elements[i].checked=false;
1122: }
1123: }
1124: }
1125:
1126: '."\n");
1127: return $chkallscript;
1128: }
1129:
1130: sub check_buttons {
1131: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1132: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1133: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1134: $buttons.='<input type="text" size="5" name="chksec" /> ';
1135: return $buttons;
1136: }
1137:
1138: # Displays the submissions for one student or a group of students
1139: sub processGroup {
1140: my ($request,$symb) = @_;
1141: my $ctr = 0;
1142: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1143: my $total = scalar(@stuchecked)-1;
1144:
1145: foreach my $student (@stuchecked) {
1146: my ($uname,$udom,$fullname) = split(/:/,$student);
1147: $env{'form.student'} = $uname;
1148: $env{'form.userdom'} = $udom;
1149: $env{'form.fullname'} = $fullname;
1150: &submission($request,$ctr,$total,$symb);
1151: $ctr++;
1152: }
1153: return '';
1154: }
1155:
1156: #------------------------------------------------------------------------------------
1157: #
1158: #-------------------------- Next few routines handles grading by student, essentially
1159: # handles essay response type problem/part
1160: #
1161: #--- Javascript to handle the submission page functionality ---
1162: sub sub_page_js {
1163: my $request = shift;
1164: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1165: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1166: function updateRadio(formname,id,weight) {
1167: var gradeBox = formname["GD_BOX"+id];
1168: var radioButton = formname["RADVAL"+id];
1169: var oldpts = formname["oldpts"+id].value;
1170: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1171: gradeBox.value = pts;
1172: var resetbox = false;
1173: if (isNaN(pts) || pts < 0) {
1174: alert("$alertmsg"+pts);
1175: for (var i=0; i<radioButton.length; i++) {
1176: if (radioButton[i].checked) {
1177: gradeBox.value = i;
1178: resetbox = true;
1179: }
1180: }
1181: if (!resetbox) {
1182: formtextbox.value = "";
1183: }
1184: return;
1185: }
1186:
1187: if (pts > weight) {
1188: var resp = confirm("You entered a value ("+pts+
1189: ") greater than the weight for the part. Accept?");
1190: if (resp == false) {
1191: gradeBox.value = oldpts;
1192: return;
1193: }
1194: }
1195:
1196: for (var i=0; i<radioButton.length; i++) {
1197: radioButton[i].checked=false;
1198: if (pts == i && pts != "") {
1199: radioButton[i].checked=true;
1200: }
1201: }
1202: updateSelect(formname,id);
1203: formname["stores"+id].value = "0";
1204: }
1205:
1206: function writeBox(formname,id,pts) {
1207: var gradeBox = formname["GD_BOX"+id];
1208: if (checkSolved(formname,id) == 'update') {
1209: gradeBox.value = pts;
1210: } else {
1211: var oldpts = formname["oldpts"+id].value;
1212: gradeBox.value = oldpts;
1213: var radioButton = formname["RADVAL"+id];
1214: for (var i=0; i<radioButton.length; i++) {
1215: radioButton[i].checked=false;
1216: if (i == oldpts) {
1217: radioButton[i].checked=true;
1218: }
1219: }
1220: }
1221: formname["stores"+id].value = "0";
1222: updateSelect(formname,id);
1223: return;
1224: }
1225:
1226: function clearRadBox(formname,id) {
1227: if (checkSolved(formname,id) == 'noupdate') {
1228: updateSelect(formname,id);
1229: return;
1230: }
1231: gradeSelect = formname["GD_SEL"+id];
1232: for (var i=0; i<gradeSelect.length; i++) {
1233: if (gradeSelect[i].selected) {
1234: var selectx=i;
1235: }
1236: }
1237: var stores = formname["stores"+id];
1238: if (selectx == stores.value) { return };
1239: var gradeBox = formname["GD_BOX"+id];
1240: gradeBox.value = "";
1241: var radioButton = formname["RADVAL"+id];
1242: for (var i=0; i<radioButton.length; i++) {
1243: radioButton[i].checked=false;
1244: }
1245: stores.value = selectx;
1246: }
1247:
1248: function checkSolved(formname,id) {
1249: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1250: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1251: if (!reply) {return "noupdate";}
1252: formname.overRideScore.value = 'yes';
1253: }
1254: return "update";
1255: }
1256:
1257: function updateSelect(formname,id) {
1258: formname["GD_SEL"+id][0].selected = true;
1259: return;
1260: }
1261:
1262: //=========== Check that a point is assigned for all the parts ============
1263: function checksubmit(formname,val,total,parttot) {
1264: formname.gradeOpt.value = val;
1265: if (val == "Save & Next") {
1266: for (i=0;i<=total;i++) {
1267: for (j=0;j<parttot;j++) {
1268: var partid = formname["partid"+i+"_"+j].value;
1269: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1270: var points = formname["GD_BOX"+i+"_"+partid].value;
1271: if (points == "") {
1272: var name = formname["name"+i].value;
1273: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1274: var resp = confirm("You did not assign a score for "+studentID+
1275: ", part "+partid+". Continue?");
1276: if (resp == false) {
1277: formname["GD_BOX"+i+"_"+partid].focus();
1278: return false;
1279: }
1280: }
1281: }
1282:
1283: }
1284: }
1285:
1286: }
1287: formname.submit();
1288: }
1289:
1290: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1291: function checkSubmitPage(formname,total) {
1292: noscore = new Array(100);
1293: var ptr = 0;
1294: for (i=1;i<total;i++) {
1295: var partid = formname["q_"+i].value;
1296: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1297: var points = formname["GD_BOX"+i+"_"+partid].value;
1298: var status = formname["solved"+i+"_"+partid].value;
1299: if (points == "" && status != "correct_by_student") {
1300: noscore[ptr] = i;
1301: ptr++;
1302: }
1303: }
1304: }
1305: if (ptr != 0) {
1306: var sense = ptr == 1 ? ": " : "s: ";
1307: var prolist = "";
1308: if (ptr == 1) {
1309: prolist = noscore[0];
1310: } else {
1311: var i = 0;
1312: while (i < ptr-1) {
1313: prolist += noscore[i]+", ";
1314: i++;
1315: }
1316: prolist += "and "+noscore[i];
1317: }
1318: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1319: if (resp == false) {
1320: return false;
1321: }
1322: }
1323:
1324: formname.submit();
1325: }
1326: SUBJAVASCRIPT
1327: }
1328:
1329: #--- javascript for essay type problem --
1330: sub sub_page_kw_js {
1331: my $request = shift;
1332: my $iconpath = $request->dir_config('lonIconsURL');
1333: &commonJSfunctions($request);
1334:
1335: my $inner_js_msg_central= (<<INNERJS);
1336: <script type="text/javascript">
1337: function checkInput() {
1338: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1339: var nmsg = opener.document.SCORE.savemsgN.value;
1340: var usrctr = document.msgcenter.usrctr.value;
1341: var newval = opener.document.SCORE["newmsg"+usrctr];
1342: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1343:
1344: var msgchk = "";
1345: if (document.msgcenter.subchk.checked) {
1346: msgchk = "msgsub,";
1347: }
1348: var includemsg = 0;
1349: for (var i=1; i<=nmsg; i++) {
1350: var opnmsg = opener.document.SCORE["savemsg"+i];
1351: var frmmsg = document.msgcenter["msg"+i];
1352: opnmsg.value = opener.checkEntities(frmmsg.value);
1353: var showflg = opener.document.SCORE["shownOnce"+i];
1354: showflg.value = "1";
1355: var chkbox = document.msgcenter["msgn"+i];
1356: if (chkbox.checked) {
1357: msgchk += "savemsg"+i+",";
1358: includemsg = 1;
1359: }
1360: }
1361: if (document.msgcenter.newmsgchk.checked) {
1362: msgchk += "newmsg"+usrctr;
1363: includemsg = 1;
1364: }
1365: imgformname = opener.document.SCORE["mailicon"+usrctr];
1366: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1367: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1368: includemsg.value = msgchk;
1369:
1370: self.close()
1371:
1372: }
1373: </script>
1374: INNERJS
1375:
1376: my $inner_js_highlight_central= (<<INNERJS);
1377: <script type="text/javascript">
1378: function updateChoice(flag) {
1379: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1380: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1381: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1382: opener.document.SCORE.refresh.value = "on";
1383: if (opener.document.SCORE.keywords.value!=""){
1384: opener.document.SCORE.submit();
1385: }
1386: self.close()
1387: }
1388: </script>
1389: INNERJS
1390:
1391: my $start_page_msg_central =
1392: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1393: {'js_ready' => 1,
1394: 'only_body' => 1,
1395: 'bgcolor' =>'#FFFFFF',});
1396: my $end_page_msg_central =
1397: &Apache::loncommon::end_page({'js_ready' => 1});
1398:
1399:
1400: my $start_page_highlight_central =
1401: &Apache::loncommon::start_page('Highlight Central',
1402: $inner_js_highlight_central,
1403: {'js_ready' => 1,
1404: 'only_body' => 1,
1405: 'bgcolor' =>'#FFFFFF',});
1406: my $end_page_highlight_central =
1407: &Apache::loncommon::end_page({'js_ready' => 1});
1408:
1409: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1410: $docopen=~s/^document\.//;
1411: my %lt = &Apache::lonlocal::texthash(
1412: keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
1413: plse => 'Please select a word or group of words from document and then click this link.',
1414: adds => 'Add selection to keyword list? Edit if desired.',
1415: comp => 'Compose Message for: ',
1416: incl => 'Include',
1417: subj => 'Subject',
1418: mesa => 'Message',
1419: new => 'New',
1420: save => 'Save',
1421: canc => 'Cancel',
1422: kehi => 'Keyword Highlight Options',
1423: txtc => 'Text Color',
1424: font => 'Font Size',
1425: );
1426: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1427:
1428: //===================== Show list of keywords ====================
1429: function keywords(formname) {
1430: var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1431: if (nret==null) return;
1432: formname.keywords.value = nret;
1433:
1434: if (formname.keywords.value != "") {
1435: formname.refresh.value = "on";
1436: formname.submit();
1437: }
1438: return;
1439: }
1440:
1441: //===================== Script to view submitted by ==================
1442: function viewSubmitter(submitter) {
1443: document.SCORE.refresh.value = "on";
1444: document.SCORE.NCT.value = "1";
1445: document.SCORE.unamedom0.value = submitter;
1446: document.SCORE.submit();
1447: return;
1448: }
1449:
1450: //===================== Script to add keyword(s) ==================
1451: function getSel() {
1452: if (document.getSelection) txt = document.getSelection();
1453: else if (document.selection) txt = document.selection.createRange().text;
1454: else return;
1455: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1456: if (cleantxt=="") {
1457: alert("$lt{'plse'}");
1458: return;
1459: }
1460: var nret = prompt("$lt{'adds'}",cleantxt);
1461: if (nret==null) return;
1462: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1463: if (document.SCORE.keywords.value != "") {
1464: document.SCORE.refresh.value = "on";
1465: document.SCORE.submit();
1466: }
1467: return;
1468: }
1469:
1470: //====================== Script for composing message ==============
1471: // preload images
1472: img1 = new Image();
1473: img1.src = "$iconpath/mailbkgrd.gif";
1474: img2 = new Image();
1475: img2.src = "$iconpath/mailto.gif";
1476:
1477: function msgCenter(msgform,usrctr,fullname) {
1478: var Nmsg = msgform.savemsgN.value;
1479: savedMsgHeader(Nmsg,usrctr,fullname);
1480: var subject = msgform.msgsub.value;
1481: var msgchk = document.SCORE["includemsg"+usrctr].value;
1482: re = /msgsub/;
1483: var shwsel = "";
1484: if (re.test(msgchk)) { shwsel = "checked" }
1485: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1486: displaySubject(checkEntities(subject),shwsel);
1487: for (var i=1; i<=Nmsg; i++) {
1488: var testmsg = "savemsg"+i+",";
1489: re = new RegExp(testmsg,"g");
1490: shwsel = "";
1491: if (re.test(msgchk)) { shwsel = "checked" }
1492: var message = document.SCORE["savemsg"+i].value;
1493: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1494: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1495: //any < is already converted to <, etc. However, only once!!
1496: }
1497: newmsg = document.SCORE["newmsg"+usrctr].value;
1498: shwsel = "";
1499: re = /newmsg/;
1500: if (re.test(msgchk)) { shwsel = "checked" }
1501: newMsg(newmsg,shwsel);
1502: msgTail();
1503: return;
1504: }
1505:
1506: function checkEntities(strx) {
1507: if (strx.length == 0) return strx;
1508: var orgStr = ["&", "<", ">", '"'];
1509: var newStr = ["&", "<", ">", """];
1510: var counter = 0;
1511: while (counter < 4) {
1512: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1513: counter++;
1514: }
1515: return strx;
1516: }
1517:
1518: function strReplace(strx, orgStr, newStr) {
1519: return strx.split(orgStr).join(newStr);
1520: }
1521:
1522: function savedMsgHeader(Nmsg,usrctr,fullname) {
1523: var height = 70*Nmsg+250;
1524: var scrollbar = "no";
1525: if (height > 600) {
1526: height = 600;
1527: scrollbar = "yes";
1528: }
1529: var xpos = (screen.width-600)/2;
1530: xpos = (xpos < 0) ? '0' : xpos;
1531: var ypos = (screen.height-height)/2-30;
1532: ypos = (ypos < 0) ? '0' : ypos;
1533:
1534: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1535: pWin.focus();
1536: pDoc = pWin.document;
1537: pDoc.$docopen;
1538: pDoc.write('$start_page_msg_central');
1539:
1540: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1541: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1542: pDoc.write("<h3><span class=\\"LC_info\\"> $lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1543:
1544: pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1545: pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1546: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1547: }
1548: function displaySubject(msg,shwsel) {
1549: pDoc = pWin.document;
1550: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1551: pDoc.write("<td>$lt{'subj'}<\\/td>");
1552: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1553: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1554: }
1555:
1556: function displaySavedMsg(ctr,msg,shwsel) {
1557: pDoc = pWin.document;
1558: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1559: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1560: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1561: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1562: }
1563:
1564: function newMsg(newmsg,shwsel) {
1565: pDoc = pWin.document;
1566: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1567: pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1568: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1569: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1570: }
1571:
1572: function msgTail() {
1573: pDoc = pWin.document;
1574: pDoc.write("<\\/table>");
1575: pDoc.write("<\\/td><\\/tr><\\/table> ");
1576: pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\"> ");
1577: pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1578: pDoc.write("<\\/form>");
1579: pDoc.write('$end_page_msg_central');
1580: pDoc.close();
1581: }
1582:
1583: //====================== Script for keyword highlight options ==============
1584: function kwhighlight() {
1585: var kwclr = document.SCORE.kwclr.value;
1586: var kwsize = document.SCORE.kwsize.value;
1587: var kwstyle = document.SCORE.kwstyle.value;
1588: var redsel = "";
1589: var grnsel = "";
1590: var blusel = "";
1591: if (kwclr=="red") {var redsel="checked"};
1592: if (kwclr=="green") {var grnsel="checked"};
1593: if (kwclr=="blue") {var blusel="checked"};
1594: var sznsel = "";
1595: var sz1sel = "";
1596: var sz2sel = "";
1597: if (kwsize=="0") {var sznsel="checked"};
1598: if (kwsize=="+1") {var sz1sel="checked"};
1599: if (kwsize=="+2") {var sz2sel="checked"};
1600: var synsel = "";
1601: var syisel = "";
1602: var sybsel = "";
1603: if (kwstyle=="") {var synsel="checked"};
1604: if (kwstyle=="<i>") {var syisel="checked"};
1605: if (kwstyle=="<b>") {var sybsel="checked"};
1606: highlightCentral();
1607: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1608: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1609: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1610: highlightend();
1611: return;
1612: }
1613:
1614: function highlightCentral() {
1615: // if (window.hwdWin) window.hwdWin.close();
1616: var xpos = (screen.width-400)/2;
1617: xpos = (xpos < 0) ? '0' : xpos;
1618: var ypos = (screen.height-330)/2-30;
1619: ypos = (ypos < 0) ? '0' : ypos;
1620:
1621: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1622: hwdWin.focus();
1623: var hDoc = hwdWin.document;
1624: hDoc.$docopen;
1625: hDoc.write('$start_page_highlight_central');
1626: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1627: hDoc.write("<h3><span class=\\"LC_info\\"> $lt{'kehi'}<\\/span><\\/h3><br /><br />");
1628:
1629: hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1630: hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1631: hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1632: }
1633:
1634: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1635: var hDoc = hwdWin.document;
1636: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1637: hDoc.write("<td align=\\"left\\">");
1638: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1639: hDoc.write("<td align=\\"left\\">");
1640: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1641: hDoc.write("<td align=\\"left\\">");
1642: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1643: hDoc.write("<\\/tr>");
1644: }
1645:
1646: function highlightend() {
1647: var hDoc = hwdWin.document;
1648: hDoc.write("<\\/table>");
1649: hDoc.write("<\\/td><\\/tr><\\/table> ");
1650: hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\"> ");
1651: hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1652: hDoc.write("<\\/form>");
1653: hDoc.write('$end_page_highlight_central');
1654: hDoc.close();
1655: }
1656:
1657: SUBJAVASCRIPT
1658: }
1659:
1660: sub get_increment {
1661: my $increment = $env{'form.increment'};
1662: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1663: $increment != .1) {
1664: $increment = 1;
1665: }
1666: return $increment;
1667: }
1668:
1669: sub gradeBox_start {
1670: return (
1671: &Apache::loncommon::start_data_table()
1672: .&Apache::loncommon::start_data_table_header_row()
1673: .'<th>'.&mt('Part').'</th>'
1674: .'<th>'.&mt('Points').'</th>'
1675: .'<th> </th>'
1676: .'<th>'.&mt('Assign Grade').'</th>'
1677: .'<th>'.&mt('Weight').'</th>'
1678: .'<th>'.&mt('Grade Status').'</th>'
1679: .&Apache::loncommon::end_data_table_header_row()
1680: );
1681: }
1682:
1683: sub gradeBox_end {
1684: return (
1685: &Apache::loncommon::end_data_table()
1686: );
1687: }
1688: #--- displays the grading box, used in essay type problem and grading by page/sequence
1689: sub gradeBox {
1690: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1691: my $checkIcon = '<img alt="'.&mt('Check Mark').
1692: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1693: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1694: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1695: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1696: $wgt = ($wgt > 0 ? $wgt : '1');
1697: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1698: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1699: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1700: my $display_part= &get_display_part($partid,$symb);
1701: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1702: [$partid]);
1703: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1704: if ($last_resets{$partid}) {
1705: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1706: }
1707: $result.=&Apache::loncommon::start_data_table_row();
1708: my $ctr = 0;
1709: my $thisweight = 0;
1710: my $increment = &get_increment();
1711:
1712: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1713: while ($thisweight<=$wgt) {
1714: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1715: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1716: $thisweight.')" value="'.$thisweight.'" '.
1717: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1718: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1719: $thisweight += $increment;
1720: $ctr++;
1721: }
1722: $radio.='</tr></table>';
1723:
1724: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1725: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1726: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1727: $wgt.')" /></td>'."\n";
1728: $line.='<td>/'.$wgt.' '.$wgtmsg.
1729: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1730: ' </td>'."\n";
1731: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1732: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1733: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1734: $line.='<option></option>'.
1735: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1736: } else {
1737: $line.='<option selected="selected"></option>'.
1738: '<option value="excused" >'.&mt('excused').'</option>';
1739: }
1740: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1741:
1742:
1743: $result .=
1744: '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1745: $result.=&Apache::loncommon::end_data_table_row();
1746: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1747: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1748: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1749: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1750: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1751: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1752: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1753: $aggtries.'" />'."\n";
1754: my $res_error;
1755: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1756: if ($res_error) {
1757: return &navmap_errormsg();
1758: }
1759: return $result;
1760: }
1761:
1762: sub handback_box {
1763: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1764: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1765: my (@respids);
1766: my @part_response_id = &flatten_responseType($responseType);
1767: foreach my $part_response_id (@part_response_id) {
1768: my ($part,$resp) = @{ $part_response_id };
1769: if ($part eq $partid) {
1770: push(@respids,$resp);
1771: }
1772: }
1773: my $result;
1774: foreach my $respid (@respids) {
1775: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1776: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1777: next if (!@$files);
1778: my $file_counter = 0;
1779: foreach my $file (@$files) {
1780: if ($file =~ /\/portfolio\//) {
1781: $file_counter++;
1782: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1783: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1784: $file_disp = "$name.$ext";
1785: $file = $file_path.$file_disp;
1786: $result.=&mt('Return commented version of [_1] to student.',
1787: '<span class="LC_filename">'.$file_disp.'</span>');
1788: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1789: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1790: }
1791: }
1792: if ($file_counter) {
1793: $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
1794: '<span class="LC_info">'.
1795: '('.&mt('File(s) will be uploaded when you click on Save & Next below.',$file_counter).')</span><br /><br />';
1796: }
1797: }
1798: return $result;
1799: }
1800:
1801: sub show_problem {
1802: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1803: my $rendered;
1804: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1805: &Apache::lonxml::remember_problem_counter();
1806: if ($mode eq 'both' or $mode eq 'text') {
1807: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1808: $env{'request.course.id'},
1809: undef,\%form);
1810: }
1811: if ($removeform) {
1812: $rendered=~s|<form(.*?)>||g;
1813: $rendered=~s|</form>||g;
1814: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1815: }
1816: my $companswer;
1817: if ($mode eq 'both' or $mode eq 'answer') {
1818: &Apache::lonxml::restore_problem_counter();
1819: $companswer=
1820: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1821: $env{'request.course.id'},
1822: %form);
1823: }
1824: if ($removeform) {
1825: $companswer=~s|<form(.*?)>||g;
1826: $companswer=~s|</form>||g;
1827: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1828: }
1829: $rendered=
1830: '<div class="LC_Box">'
1831: .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
1832: .$rendered
1833: .'</div>';
1834: $companswer=
1835: '<div class="LC_Box">'
1836: .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
1837: .$companswer
1838: .'</div>';
1839: my $result;
1840: if ($mode eq 'both') {
1841: $result=$rendered.$companswer;
1842: } elsif ($mode eq 'text') {
1843: $result=$rendered;
1844: } elsif ($mode eq 'answer') {
1845: $result=$companswer;
1846: }
1847: return $result;
1848: }
1849:
1850: sub files_exist {
1851: my ($r, $symb) = @_;
1852: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1853:
1854: foreach my $student (@students) {
1855: my ($uname,$udom,$fullname) = split(/:/,$student);
1856: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1857: $udom,$uname);
1858: my ($string,$timestamp)= &get_last_submission(\%record);
1859: foreach my $submission (@$string) {
1860: my ($partid,$respid) =
1861: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1862: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1863: \%record);
1864: return 1 if (@$files);
1865: }
1866: }
1867: return 0;
1868: }
1869:
1870: sub download_all_link {
1871: my ($r,$symb) = @_;
1872: unless (&files_exist($r, $symb)) {
1873: $r->print(&mt('There are currently no submitted documents.'));
1874: return;
1875: }
1876:
1877: my $all_students =
1878: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1879:
1880: my $parts =
1881: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1882:
1883: my $identifier = &Apache::loncommon::get_cgi_id();
1884: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1885: 'cgi.'.$identifier.'.symb' => $symb,
1886: 'cgi.'.$identifier.'.parts' => $parts,});
1887: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1888: &mt('Download All Submitted Documents').'</a>');
1889: return;
1890: }
1891:
1892: sub submit_download_link {
1893: my ($request,$symb) = @_;
1894: if (!$symb) { return ''; }
1895: #FIXME: Figure out which type of problem this is and provide appropriate download
1896: &download_all_link($request,$symb);
1897: }
1898:
1899: sub build_section_inputs {
1900: my $section_inputs;
1901: if ($env{'form.section'} eq '') {
1902: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1903: } else {
1904: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1905: foreach my $section (@sections) {
1906: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1907: }
1908: }
1909: return $section_inputs;
1910: }
1911:
1912: # --------------------------- show submissions of a student, option to grade
1913: sub submission {
1914: my ($request,$counter,$total,$symb) = @_;
1915: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1916: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1917: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1918: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1919:
1920: my $probtitle=&Apache::lonnet::gettitle($symb);
1921: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1922:
1923: if (!&canview($usec)) {
1924: $request->print('<span class="LC_warning">Unable to view requested student.('.
1925: $uname.':'.$udom.' in section '.$usec.' in course id '.
1926: $env{'request.course.id'}.')</span>');
1927: return;
1928: }
1929:
1930: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1931: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1932: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1933: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1934: my $checkIcon = '<img alt="'.&mt('Check Mark').
1935: '" src="'.$request->dir_config('lonIconsURL').
1936: '/check.gif" height="16" border="0" />';
1937:
1938: my %old_essays;
1939: # header info
1940: if ($counter == 0) {
1941: &sub_page_js($request);
1942: &sub_page_kw_js($request);
1943:
1944: # option to display problem, only once else it cause problems
1945: # with the form later since the problem has a form.
1946: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1947: my $mode;
1948: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1949: $mode='both';
1950: } elsif ($env{'form.vProb'} eq 'yes') {
1951: $mode='text';
1952: } elsif ($env{'form.vAns'} eq 'yes') {
1953: $mode='answer';
1954: }
1955: &Apache::lonxml::clear_problem_counter();
1956: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1957: }
1958:
1959: # kwclr is the only variable that is guaranteed to be non blank
1960: # if this subroutine has been called once.
1961: my %keyhash = ();
1962: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1963: if (1) {
1964: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1965: $env{'course.'.$env{'request.course.id'}.'.domain'},
1966: $env{'course.'.$env{'request.course.id'}.'.num'});
1967:
1968: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1969: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1970: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1971: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1972: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1973: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1974: $keyhash{$symb.'_subject'} : $probtitle;
1975: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1976: }
1977: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1978: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1979: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1980: '<input type="hidden" name="command" value="handgrade" />'."\n".
1981: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1982: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1983: '<input type="hidden" name="refresh" value="off" />'."\n".
1984: '<input type="hidden" name="studentNo" value="" />'."\n".
1985: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1986: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1987: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1988: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1989: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1990: &build_section_inputs().
1991: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1992: '<input type="hidden" name="NCT"'.
1993: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1994: # if ($env{'form.handgrade'} eq 'yes') {
1995: if (1) {
1996: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1997: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1998: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1999: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
2000: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
2001: '<input type="hidden" name="shownSub" value="0" />'."\n".
2002: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
2003: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
2004: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
2005: }
2006: }
2007:
2008: my ($cts,$prnmsg) = (1,'');
2009: while ($cts <= $env{'form.savemsgN'}) {
2010: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
2011: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
2012: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
2013: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2014: '" />'."\n".
2015: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2016: $cts++;
2017: }
2018: $request->print($prnmsg);
2019:
2020: # if ($env{'form.handgrade'} eq 'yes') {
2021: if (1) {
2022:
2023: my %lt = &Apache::lonlocal::texthash(
2024: keyw => 'Keyword Options',
2025: past => 'Paste Selection to List',
2026: high => 'Hightlight Attribute',
2027: );
2028: #
2029: # Print out the keyword options line
2030: #
2031: $request->print(<<KEYWORDS);
2032: <br /><b>$lt{'keyw'}:</b>
2033: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
2034: <a href="#" onmousedown="javascript:getSel(); return false"
2035: CLASS="page">$lt{'past'}</a>
2036: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
2037: KEYWORDS
2038: #
2039: # Load the other essays for similarity check
2040: #
2041: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2042: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2043: $apath=&escape($apath);
2044: $apath=~s/\W/\_/gs;
2045: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
2046: }
2047: }
2048:
2049: # This is where output for one specific student would start
2050: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2051: $request->print(
2052: "\n\n"
2053: .'<div class="LC_grade_show_user'.$add_class.'">'
2054: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2055: ."\n"
2056: );
2057:
2058: # Show additional functions if allowed
2059: if ($perm{'vgr'}) {
2060: $request->print(
2061: &Apache::loncommon::track_student_link(
2062: &mt('View recent activity'),
2063: $uname,$udom,'check')
2064: .' '
2065: );
2066: }
2067: if ($perm{'opa'}) {
2068: $request->print(
2069: &Apache::loncommon::pprmlink(
2070: &mt('Set/Change parameters'),
2071: $uname,$udom,$symb,'check'));
2072: }
2073:
2074: # Show Problem
2075: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2076: my $mode;
2077: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2078: $mode='both';
2079: } elsif ($env{'form.vProb'} eq 'all' ) {
2080: $mode='text';
2081: } elsif ($env{'form.vAns'} eq 'all') {
2082: $mode='answer';
2083: }
2084: &Apache::lonxml::clear_problem_counter();
2085: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2086: }
2087:
2088: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2089: my $res_error;
2090: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2091: if ($res_error) {
2092: $request->print(&navmap_errormsg());
2093: return;
2094: }
2095:
2096: # Display student info
2097: $request->print(($counter == 0 ? '' : '<br />'));
2098:
2099: my $result='<div class="LC_Box">'
2100: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2101: $result.='<input type="hidden" name="name'.$counter.
2102: '" value="'.$env{'form.fullname'}.'" />'."\n";
2103: # if ($env{'form.handgrade'} eq 'no') {
2104: if (1) {
2105: $result.='<p class="LC_info">'
2106: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2107: ."</p>\n";
2108: }
2109:
2110: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2111: my $fullname;
2112: my $col_fullnames = [];
2113: # if ($env{'form.handgrade'} eq 'yes') {
2114: if (1) {
2115: (my $sub_result,$fullname,$col_fullnames)=
2116: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2117: $counter);
2118: $result.=$sub_result;
2119: }
2120: $request->print($result."\n");
2121:
2122: # print student answer/submission
2123: # Options are (1) Handgraded submission only
2124: # (2) Last submission, includes submission that is not handgraded
2125: # (for multi-response type part)
2126: # (3) Last submission plus the parts info
2127: # (4) The whole record for this student
2128: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2129: my ($string,$timestamp)= &get_last_submission(\%record);
2130:
2131: my $lastsubonly;
2132:
2133: if ($$timestamp eq '') {
2134: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2135: } else {
2136: $lastsubonly =
2137: '<div class="LC_grade_submissions_body">'
2138: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2139:
2140: my %seenparts;
2141: my @part_response_id = &flatten_responseType($responseType);
2142: foreach my $part (@part_response_id) {
2143: next if ($env{'form.lastSub'} eq 'hdgrade'
2144: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2145:
2146: my ($partid,$respid) = @{ $part };
2147: my $display_part=&get_display_part($partid,$symb);
2148: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2149: if (exists($seenparts{$partid})) { next; }
2150: $seenparts{$partid}=1;
2151: my $submitby='<b>Part:</b> '.$display_part.
2152: ' <b>Collaborative submission by:</b> '.
2153: '<a href="javascript:viewSubmitter(\''.
2154: $env{"form.$uname:$udom:$partid:submitted_by"}.
2155: '\');" target="_self">'.
2156: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2157: $request->print($submitby);
2158: next;
2159: }
2160: my $responsetype = $responseType->{$partid}->{$respid};
2161: if (!exists($record{"resource.$partid.$respid.submission"})) {
2162: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2163: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2164: ' <span class="LC_internal_info">'.
2165: '('.&mt('Response ID: [_1]',$respid).')'.
2166: '</span> '.
2167: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2168: next;
2169: }
2170: foreach my $submission (@$string) {
2171: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2172: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2173: my ($ressub,$hide,$subval) = split(/:/,$submission,3);
2174: # Similarity check
2175: my $similar='';
2176: my ($type,$trial,$rndseed);
2177: if ($hide eq 'rand') {
2178: $type = 'randomizetry';
2179: $trial = $record{"resource.$partid.tries"};
2180: $rndseed = $record{"resource.$partid.rndseed"};
2181: }
2182: if($env{'form.checkPlag'}){
2183: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2184: &most_similar($uname,$udom,$subval,\%old_essays);
2185: if ($osim) {
2186: $osim=int($osim*100.0);
2187: my %old_course_desc =
2188: &Apache::lonnet::coursedescription($ocrsid,
2189: {'one_time' => 1});
2190:
2191: if ($hide eq 'anon') {
2192: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2193: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2194: } else {
2195: $similar="<hr /><h3><span class=\"LC_warning\">".
2196: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2197: $osim,
2198: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2199: $old_course_desc{'description'},
2200: $old_course_desc{'num'},
2201: $old_course_desc{'domain'}).
2202: '</span></h3><blockquote><i>'.
2203: &keywords_highlight($oessay).
2204: '</i></blockquote><hr />';
2205: }
2206: }
2207: }
2208: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2209: undef,$type,$trial,$rndseed);
2210: if ($env{'form.lastSub'} eq 'lastonly' ||
2211: ($env{'form.lastSub'} eq 'hdgrade' &&
2212: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2213: my $display_part=&get_display_part($partid,$symb);
2214: $lastsubonly.='<div class="LC_grade_submission_part">'.
2215: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2216: ' <span class="LC_internal_info">'.
2217: '('.&mt('Response ID: [_1]',$respid).')'.
2218: '</span> ';
2219: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2220: if (@$files) {
2221: if ($hide eq 'anon') {
2222: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2223: } else {
2224: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
2225: foreach my $file (@$files) {
2226: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2227: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
2228: }
2229: }
2230: $lastsubonly.='<br />';
2231: }
2232: if ($hide eq 'anon') {
2233: $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>';
2234: } else {
2235: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2236: &cleanRecord($subval,$responsetype,$symb,$partid,
2237: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2238: }
2239: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2240: $lastsubonly.='</div>';
2241: }
2242: }
2243: }
2244: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2245: }
2246: $request->print($lastsubonly);
2247: } elsif ($env{'form.lastSub'} eq 'datesub') {
2248: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2249: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2250: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2251: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2252: $env{'request.course.id'},
2253: $last,'.submission',
2254: 'Apache::grades::keywords_highlight'));
2255: }
2256: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2257: .$udom.'" />'."\n");
2258: # return if view submission with no grading option
2259: if (!&canmodify($usec)) {
2260: $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
2261: return;
2262: } else {
2263: $request->print('</div>'."\n");
2264: }
2265:
2266: # essay grading message center
2267: # if ($env{'form.handgrade'} eq 'yes') {
2268: if (1) {
2269: my $result='<div class="LC_grade_message_center">';
2270:
2271: $result.='<div class="LC_grade_message_center_header">'.
2272: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2273: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2274: my $msgfor = $givenn.' '.$lastname;
2275: if (scalar(@$col_fullnames) > 0) {
2276: my $lastone = pop(@$col_fullnames);
2277: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2278: }
2279: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2280: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2281: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2282: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2283: ',\''.$msgfor.'\');" target="_self">'.
2284: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2285: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2286: '<img src="'.$request->dir_config('lonIconsURL').
2287: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2288: '<br /> ('.
2289: &mt('Message will be sent when you click on Save & Next below.').")\n";
2290: $result.='</div></div>';
2291: $request->print($result);
2292: }
2293:
2294: my %seen = ();
2295: my @partlist;
2296: my @gradePartRespid;
2297: my @part_response_id = &flatten_responseType($responseType);
2298: $request->print(
2299: '<div class="LC_Box">'
2300: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2301: );
2302: $request->print(&gradeBox_start());
2303: foreach my $part_response_id (@part_response_id) {
2304: my ($partid,$respid) = @{ $part_response_id };
2305: my $part_resp = join('_',@{ $part_response_id });
2306: next if ($seen{$partid} > 0);
2307: $seen{$partid}++;
2308: next if ($$handgrade{$part_resp} ne 'yes'
2309: && $env{'form.lastSub'} eq 'hdgrade');
2310: push(@partlist,$partid);
2311: push(@gradePartRespid,$partid.'.'.$respid);
2312: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2313: }
2314: $request->print(&gradeBox_end()); # </div>
2315: $request->print('</div>');
2316:
2317: $request->print('<div class="LC_grade_info_links">');
2318: $request->print('</div>');
2319:
2320: $result='<input type="hidden" name="partlist'.$counter.
2321: '" value="'.(join ":",@partlist).'" />'."\n";
2322: $result.='<input type="hidden" name="gradePartRespid'.
2323: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2324: my $ctr = 0;
2325: while ($ctr < scalar(@partlist)) {
2326: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2327: $partlist[$ctr].'" />'."\n";
2328: $ctr++;
2329: }
2330: $request->print($result.''."\n");
2331:
2332: # Done with printing info for one student
2333:
2334: $request->print('</div>');#LC_grade_show_user
2335:
2336:
2337: # print end of form
2338: if ($counter == $total) {
2339: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2340: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2341: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2342: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2343: my $ntstu ='<select name="NTSTU">'.
2344: '<option>1</option><option>2</option>'.
2345: '<option>3</option><option>5</option>'.
2346: '<option>7</option><option>10</option></select>'."\n";
2347: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2348: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2349: $endform.=&mt('[_1]student(s)',$ntstu);
2350: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2351: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2352: '<input type="button" value="'.&mt('Next').'" '.
2353: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2354: $endform.='<span class="LC_warning">'.
2355: &mt('(Next and Previous (student) do not save the scores.)').
2356: '</span>'."\n" ;
2357: $endform.="<input type='hidden' value='".&get_increment().
2358: "' name='increment' />";
2359: $endform.='</td></tr></table></form>';
2360: $request->print($endform);
2361: }
2362: return '';
2363: }
2364:
2365: sub check_collaborators {
2366: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2367: my ($result,@col_fullnames);
2368: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2369: foreach my $part (keys(%$handgrade)) {
2370: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2371: '.maxcollaborators',
2372: $symb,$udom,$uname);
2373: next if ($ncol <= 0);
2374: $part =~ s/\_/\./g;
2375: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2376: my (@good_collaborators, @bad_collaborators);
2377: foreach my $possible_collaborator
2378: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2379: $possible_collaborator =~ s/[\$\^\(\)]//g;
2380: next if ($possible_collaborator eq '');
2381: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2382: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2383: next if ($co_name eq $uname && $co_dom eq $udom);
2384: # Doing this grep allows 'fuzzy' specification
2385: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2386: keys(%$classlist));
2387: if (! scalar(@matches)) {
2388: push(@bad_collaborators, $possible_collaborator);
2389: } else {
2390: push(@good_collaborators, @matches);
2391: }
2392: }
2393: if (scalar(@good_collaborators) != 0) {
2394: $result.='<br />'.&mt('Collaborators:').'<ol>';
2395: foreach my $name (@good_collaborators) {
2396: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2397: push(@col_fullnames, $givenn.' '.$lastname);
2398: $result.='<li>'.$fullname->{$name}.'</li>';
2399: }
2400: $result.='</ol><br />'."\n";
2401: my ($part)=split(/\./,$part);
2402: $result.='<input type="hidden" name="collaborator'.$counter.
2403: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2404: "\n";
2405: }
2406: if (scalar(@bad_collaborators) > 0) {
2407: $result.='<div class="LC_warning">';
2408: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2409: $result .= '</div>';
2410: }
2411: if (scalar(@bad_collaborators > $ncol)) {
2412: $result .= '<div class="LC_warning">';
2413: $result .= &mt('This student has submitted too many '.
2414: 'collaborators. Maximum is [_1].',$ncol);
2415: $result .= '</div>';
2416: }
2417: }
2418: return ($result,$fullname,\@col_fullnames);
2419: }
2420:
2421: #--- Retrieve the last submission for all the parts
2422: sub get_last_submission {
2423: my ($returnhash)=@_;
2424: my (@string,$timestamp,%lasthidden);
2425: if ($$returnhash{'version'}) {
2426: my %lasthash=();
2427: my ($version);
2428: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2429: foreach my $key (sort(split(/\:/,
2430: $$returnhash{$version.':keys'}))) {
2431: $lasthash{$key}=$$returnhash{$version.':'.$key};
2432: $timestamp =
2433: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2434: }
2435: }
2436: my (%typeparts,%randombytry);
2437: my $showsurv =
2438: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2439: foreach my $key (sort(keys(%lasthash))) {
2440: if ($key =~ /\.type$/) {
2441: if (($lasthash{$key} eq 'anonsurvey') ||
2442: ($lasthash{$key} eq 'anonsurveycred') ||
2443: ($lasthash{$key} eq 'randomizetry')) {
2444: my ($ign,@parts) = split(/\./,$key);
2445: pop(@parts);
2446: my $id = join('.',@parts);
2447: if ($lasthash{$key} eq 'randomizetry') {
2448: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2449: } else {
2450: unless ($showsurv) {
2451: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2452: }
2453: }
2454: delete($lasthash{$key});
2455: }
2456: }
2457: }
2458: my @hidden = keys(%typeparts);
2459: my @randomize = keys(%randombytry);
2460: foreach my $key (keys(%lasthash)) {
2461: next if ($key !~ /\.submission$/);
2462: my $hide;
2463: if (@hidden) {
2464: foreach my $id (@hidden) {
2465: if ($key =~ /^\Q$id\E/) {
2466: $hide = 'anon';
2467: last;
2468: }
2469: }
2470: }
2471: unless ($hide) {
2472: if (@randomize) {
2473: foreach my $id (@hidden) {
2474: if ($key =~ /^\Q$id\E/) {
2475: $hide = 'rand';
2476: last;
2477: }
2478: }
2479: }
2480: }
2481: my ($partid,$foo) = split(/submission$/,$key);
2482: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2483: '<span class="LC_warning">Draft Copy</span> ' : '';
2484: push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
2485: }
2486: }
2487: if (!@string) {
2488: $string[0] =
2489: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2490: }
2491: return (\@string,\$timestamp);
2492: }
2493:
2494: #--- High light keywords, with style choosen by user.
2495: sub keywords_highlight {
2496: my $string = shift;
2497: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2498: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2499: (my $styleoff = $styleon) =~ s/\</\<\//;
2500: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2501: foreach my $keyword (@keylist) {
2502: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2503: }
2504: return $string;
2505: }
2506:
2507: #--- Called from submission routine
2508: sub processHandGrade {
2509: my ($request,$symb) = @_;
2510: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2511: my $button = $env{'form.gradeOpt'};
2512: my $ngrade = $env{'form.NCT'};
2513: my $ntstu = $env{'form.NTSTU'};
2514: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2515: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2516:
2517: if ($button eq 'Save & Next') {
2518: my $ctr = 0;
2519: while ($ctr < $ngrade) {
2520: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2521: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2522: if ($errorflag eq 'no_score') {
2523: $ctr++;
2524: next;
2525: }
2526: if ($errorflag eq 'not_allowed') {
2527: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2528: $ctr++;
2529: next;
2530: }
2531: my $includemsg = $env{'form.includemsg'.$ctr};
2532: my ($subject,$message,$msgstatus) = ('','','');
2533: my $restitle = &Apache::lonnet::gettitle($symb);
2534: my ($feedurl,$showsymb) =
2535: &get_feedurl_and_symb($symb,$uname,$udom);
2536: my $messagetail;
2537: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2538: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2539: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2540: $subject.=' ['.$restitle.']';
2541: my (@msgnum) = split(/,/,$includemsg);
2542: foreach (@msgnum) {
2543: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2544: }
2545: $message =&Apache::lonfeedback::clear_out_html($message);
2546: if ($env{'form.withgrades'.$ctr}) {
2547: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2548: $messagetail = " for <a href=\"".
2549: $feedurl."?symb=$showsymb\">$restitle</a>";
2550: }
2551: $msgstatus =
2552: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2553: $message.$messagetail,
2554: undef,$feedurl,undef,
2555: undef,undef,$showsymb,
2556: $restitle);
2557: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2558: $msgstatus.'<br />');
2559: }
2560: if ($env{'form.collaborator'.$ctr}) {
2561: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2562: foreach my $collabstr (@collabstrs) {
2563: my ($part,@collaborators) = split(/:/,$collabstr);
2564: foreach my $collaborator (@collaborators) {
2565: my ($errorflag,$pts,$wgt) =
2566: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2567: $env{'form.unamedom'.$ctr},$part);
2568: if ($errorflag eq 'not_allowed') {
2569: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2570: next;
2571: } elsif ($message ne '') {
2572: my ($baseurl,$showsymb) =
2573: &get_feedurl_and_symb($symb,$collaborator,
2574: $udom);
2575: if ($env{'form.withgrades'.$ctr}) {
2576: $messagetail = " for <a href=\"".
2577: $baseurl."?symb=$showsymb\">$restitle</a>";
2578: }
2579: $msgstatus =
2580: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2581: }
2582: }
2583: }
2584: }
2585: $ctr++;
2586: }
2587: }
2588:
2589: # if ($env{'form.handgrade'} eq 'yes') {
2590: if (1) {
2591: # Keywords sorted in alphabatical order
2592: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2593: my %keyhash = ();
2594: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2595: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2596: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2597: $env{'form.keywords'} = join(' ',@keywords);
2598: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2599: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2600: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2601: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2602: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2603:
2604: # message center - Order of message gets changed. Blank line is eliminated.
2605: # New messages are saved in env for the next student.
2606: # All messages are saved in nohist_handgrade.db
2607: my ($ctr,$idx) = (1,1);
2608: while ($ctr <= $env{'form.savemsgN'}) {
2609: if ($env{'form.savemsg'.$ctr} ne '') {
2610: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2611: $idx++;
2612: }
2613: $ctr++;
2614: }
2615: $ctr = 0;
2616: while ($ctr < $ngrade) {
2617: if ($env{'form.newmsg'.$ctr} ne '') {
2618: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2619: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2620: $idx++;
2621: }
2622: $ctr++;
2623: }
2624: $env{'form.savemsgN'} = --$idx;
2625: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2626: my $putresult = &Apache::lonnet::put
2627: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2628: }
2629: # Called by Save & Refresh from Highlight Attribute Window
2630: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2631: if ($env{'form.refresh'} eq 'on') {
2632: my ($ctr,$total) = (0,0);
2633: while ($ctr < $ngrade) {
2634: $total++ if $env{'form.unamedom'.$ctr} ne '';
2635: $ctr++;
2636: }
2637: $env{'form.NTSTU'}=$ngrade;
2638: $ctr = 0;
2639: while ($ctr < $total) {
2640: my $processUser = $env{'form.unamedom'.$ctr};
2641: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2642: $env{'form.fullname'} = $$fullname{$processUser};
2643: &submission($request,$ctr,$total-1,$symb);
2644: $ctr++;
2645: }
2646: return '';
2647: }
2648:
2649: # Get the next/previous one or group of students
2650: my $firststu = $env{'form.unamedom0'};
2651: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2652: my $ctr = 2;
2653: while ($laststu eq '') {
2654: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2655: $ctr++;
2656: $laststu = $firststu if ($ctr > $ngrade);
2657: }
2658:
2659: my (@parsedlist,@nextlist);
2660: my ($nextflg) = 0;
2661: foreach my $item (sort
2662: {
2663: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2664: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2665: }
2666: return $a cmp $b;
2667: } (keys(%$fullname))) {
2668: # FIXME: this is fishy, looks like the button label
2669: if ($nextflg == 1 && $button =~ /Next$/) {
2670: push(@parsedlist,$item);
2671: }
2672: $nextflg = 1 if ($item eq $laststu);
2673: if ($button eq 'Previous') {
2674: last if ($item eq $firststu);
2675: push(@parsedlist,$item);
2676: }
2677: }
2678: $ctr = 0;
2679: # FIXME: this is fishy, looks like the button label
2680: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2681: my $res_error;
2682: my ($partlist) = &response_type($symb,\$res_error);
2683: if ($res_error) {
2684: $request->print(&navmap_errormsg());
2685: return;
2686: }
2687: foreach my $student (@parsedlist) {
2688: my $submitonly=$env{'form.submitonly'};
2689: my ($uname,$udom) = split(/:/,$student);
2690:
2691: if ($submitonly eq 'queued') {
2692: my %queue_status =
2693: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2694: $udom,$uname);
2695: next if (!defined($queue_status{'gradingqueue'}));
2696: }
2697:
2698: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2699: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2700: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2701: my $submitted = 0;
2702: my $ungraded = 0;
2703: my $incorrect = 0;
2704: foreach my $item (keys(%status)) {
2705: $submitted = 1 if ($status{$item} ne 'nothing');
2706: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2707: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2708: my ($foo,$partid,$foo1) = split(/\./,$item);
2709: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2710: $submitted = 0;
2711: }
2712: }
2713: next if (!$submitted && ($submitonly eq 'yes' ||
2714: $submitonly eq 'incorrect' ||
2715: $submitonly eq 'graded'));
2716: next if (!$ungraded && ($submitonly eq 'graded'));
2717: next if (!$incorrect && $submitonly eq 'incorrect');
2718: }
2719: push(@nextlist,$student) if ($ctr < $ntstu);
2720: last if ($ctr == $ntstu);
2721: $ctr++;
2722: }
2723:
2724: $ctr = 0;
2725: my $total = scalar(@nextlist)-1;
2726:
2727: foreach (sort(@nextlist)) {
2728: my ($uname,$udom,$submitter) = split(/:/);
2729: $env{'form.student'} = $uname;
2730: $env{'form.userdom'} = $udom;
2731: $env{'form.fullname'} = $$fullname{$_};
2732: &submission($request,$ctr,$total,$symb);
2733: $ctr++;
2734: }
2735: if ($total < 0) {
2736: my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
2737: $request->print($the_end);
2738: }
2739: return '';
2740: }
2741:
2742: #---- Save the score and award for each student, if changed
2743: sub saveHandGrade {
2744: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2745: my @version_parts;
2746: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2747: $env{'request.course.id'});
2748: if (!&canmodify($usec)) { return('not_allowed'); }
2749: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2750: my @parts_graded;
2751: my %newrecord = ();
2752: my ($pts,$wgt) = ('','');
2753: my %aggregate = ();
2754: my $aggregateflag = 0;
2755: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2756: foreach my $new_part (@parts) {
2757: #collaborator ($submi may vary for different parts
2758: if ($submitter && $new_part ne $part) { next; }
2759: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2760: if ($dropMenu eq 'excused') {
2761: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2762: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2763: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2764: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2765: }
2766: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2767: }
2768: } elsif ($dropMenu eq 'reset status'
2769: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2770: foreach my $key (keys(%record)) {
2771: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2772: }
2773: $newrecord{'resource.'.$new_part.'.regrader'}=
2774: "$env{'user.name'}:$env{'user.domain'}";
2775: my $totaltries = $record{'resource.'.$part.'.tries'};
2776:
2777: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2778: [$new_part]);
2779: my $aggtries =$totaltries;
2780: if ($last_resets{$new_part}) {
2781: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2782: $new_part);
2783: }
2784:
2785: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2786: if ($aggtries > 0) {
2787: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2788: $aggregateflag = 1;
2789: }
2790: } elsif ($dropMenu eq '') {
2791: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2792: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2793: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2794: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2795: next;
2796: }
2797: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2798: $env{'form.WGT'.$newflg.'_'.$new_part};
2799: my $partial= $pts/$wgt;
2800: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2801: #do not update score for part if not changed.
2802: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2803: next;
2804: } else {
2805: push(@parts_graded,$new_part);
2806: }
2807: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2808: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2809: }
2810: my $reckey = 'resource.'.$new_part.'.solved';
2811: if ($partial == 0) {
2812: if ($record{$reckey} ne 'incorrect_by_override') {
2813: $newrecord{$reckey} = 'incorrect_by_override';
2814: }
2815: } else {
2816: if ($record{$reckey} ne 'correct_by_override') {
2817: $newrecord{$reckey} = 'correct_by_override';
2818: }
2819: }
2820: if ($submitter &&
2821: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2822: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2823: }
2824: $newrecord{'resource.'.$new_part.'.regrader'}=
2825: "$env{'user.name'}:$env{'user.domain'}";
2826: }
2827: # unless problem has been graded, set flag to version the submitted files
2828: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2829: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2830: $dropMenu eq 'reset status')
2831: {
2832: push(@version_parts,$new_part);
2833: }
2834: }
2835: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2836: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2837:
2838: if (%newrecord) {
2839: if (@version_parts) {
2840: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2841: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2842: @newrecord{@changed_keys} = @record{@changed_keys};
2843: foreach my $new_part (@version_parts) {
2844: &handback_files($request,$symb,$stuname,$domain,$newflg,
2845: $new_part,\%newrecord);
2846: }
2847: }
2848: &Apache::lonnet::cstore(\%newrecord,$symb,
2849: $env{'request.course.id'},$domain,$stuname);
2850: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2851: $cdom,$cnum,$domain,$stuname);
2852: }
2853: if ($aggregateflag) {
2854: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2855: $cdom,$cnum);
2856: }
2857: return ('',$pts,$wgt);
2858: }
2859:
2860: sub check_and_remove_from_queue {
2861: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2862: my @ungraded_parts;
2863: foreach my $part (@{$parts}) {
2864: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2865: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2866: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2867: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2868: ) {
2869: push(@ungraded_parts, $part);
2870: }
2871: }
2872: if ( !@ungraded_parts ) {
2873: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2874: $cnum,$domain,$stuname);
2875: }
2876: }
2877:
2878: sub handback_files {
2879: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2880: my $portfolio_root = '/userfiles/portfolio';
2881: my $res_error;
2882: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2883: if ($res_error) {
2884: $request->print('<br />'.&navmap_errormsg().'<br />');
2885: return;
2886: }
2887: my @handedback;
2888: my $file_msg;
2889: my @part_response_id = &flatten_responseType($responseType);
2890: foreach my $part_response_id (@part_response_id) {
2891: my ($part_id,$resp_id) = @{ $part_response_id };
2892: my $part_resp = join('_',@{ $part_response_id });
2893: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
2894: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
2895: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2896: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
2897: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
2898: my ($directory,$answer_file) =
2899: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
2900: my ($answer_name,$answer_ver,$answer_ext) =
2901: &file_name_version_ext($answer_file);
2902: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2903: my $getpropath = 1;
2904: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
2905: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2906: # fix file name
2907: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2908: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2909: $newflg.'_'.$part_resp.'_returndoc'.$counter,
2910: $save_file_name);
2911: if ($result !~ m|^/uploaded/|) {
2912: $request->print('<br /><span class="LC_error">'.
2913: &mt('An error occurred ([_1]) while trying to upload [_2].',
2914: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
2915: '</span>');
2916: } else {
2917: # mark the file as read only
2918: push(@handedback,$save_file_name);
2919: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2920: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2921: }
2922: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2923: $file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
2924: }
2925: $request->print('<br />'.&mt('[_1] will be the uploaded file name [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
2926: }
2927: }
2928: }
2929: }
2930: if (@handedback > 0) {
2931: $request->print('<br />');
2932: my @what = ($symb,$env{'request.course.id'},'handback');
2933: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
2934: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
2935: my ($subject,$message);
2936: if (scalar(@handedback) == 1) {
2937: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
2938: $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
2939: } else {
2940: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
2941: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
2942: }
2943: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
2944: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
2945: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
2946: my ($feedurl,$showsymb) =
2947: &get_feedurl_and_symb($symb,$domain,$stuname);
2948: my $restitle = &Apache::lonnet::gettitle($symb);
2949: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
2950: my $msgstatus =
2951: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
2952: $message,undef,$feedurl,undef,undef,undef,$showsymb,
2953: $restitle);
2954: if ($msgstatus) {
2955: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
2956: }
2957: }
2958: return;
2959: }
2960:
2961: sub get_feedurl_and_symb {
2962: my ($symb,$uname,$udom) = @_;
2963: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2964: $url = &Apache::lonnet::clutter($url);
2965: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2966: $symb,$udom,$uname);
2967: if ($encrypturl =~ /^yes$/i) {
2968: &Apache::lonenc::encrypted(\$url,1);
2969: &Apache::lonenc::encrypted(\$symb,1);
2970: }
2971: return ($url,$symb);
2972: }
2973:
2974: sub get_submitted_files {
2975: my ($udom,$uname,$partid,$respid,$record) = @_;
2976: my @files;
2977: if ($$record{"resource.$partid.$respid.portfiles"}) {
2978: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2979: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2980: push(@files,$file_url.$file);
2981: }
2982: }
2983: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2984: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2985: }
2986: return (\@files);
2987: }
2988:
2989: # ----------- Provides number of tries since last reset.
2990: sub get_num_tries {
2991: my ($record,$last_reset,$part) = @_;
2992: my $timestamp = '';
2993: my $num_tries = 0;
2994: if ($$record{'version'}) {
2995: for (my $version=$$record{'version'};$version>=1;$version--) {
2996: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2997: $timestamp = $$record{$version.':timestamp'};
2998: if ($timestamp > $last_reset) {
2999: $num_tries ++;
3000: } else {
3001: last;
3002: }
3003: }
3004: }
3005: }
3006: return $num_tries;
3007: }
3008:
3009: # ----------- Determine decrements required in aggregate totals
3010: sub decrement_aggs {
3011: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3012: my %decrement = (
3013: attempts => 0,
3014: users => 0,
3015: correct => 0
3016: );
3017: $decrement{'attempts'} = $aggtries;
3018: if ($solvedstatus =~ /^correct/) {
3019: $decrement{'correct'} = 1;
3020: }
3021: if ($aggtries == $totaltries) {
3022: $decrement{'users'} = 1;
3023: }
3024: foreach my $type (keys(%decrement)) {
3025: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3026: }
3027: return;
3028: }
3029:
3030: # ----------- Determine timestamps for last reset of aggregate totals for parts
3031: sub get_last_resets {
3032: my ($symb,$courseid,$partids) =@_;
3033: my %last_resets;
3034: my $cdom = $env{'course.'.$courseid.'.domain'};
3035: my $cname = $env{'course.'.$courseid.'.num'};
3036: my @keys;
3037: foreach my $part (@{$partids}) {
3038: push(@keys,"$symb\0$part\0resettime");
3039: }
3040: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3041: $cdom,$cname);
3042: foreach my $part (@{$partids}) {
3043: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3044: }
3045: return %last_resets;
3046: }
3047:
3048: # ----------- Handles creating versions for portfolio files as answers
3049: sub version_portfiles {
3050: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3051: my $version_parts = join('|',@$v_flag);
3052: my @returned_keys;
3053: my $parts = join('|', @$parts_graded);
3054: my $portfolio_root = '/userfiles/portfolio';
3055: foreach my $key (keys(%$record)) {
3056: my $new_portfiles;
3057: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3058: my @versioned_portfiles;
3059: my @portfiles = split(/\s*,\s*/,$$record{$key});
3060: foreach my $file (@portfiles) {
3061: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3062: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3063: my ($answer_name,$answer_ver,$answer_ext) =
3064: &file_name_version_ext($answer_file);
3065: my $getpropath = 1;
3066: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
3067: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
3068: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3069: if ($new_answer ne 'problem getting file') {
3070: push(@versioned_portfiles, $directory.$new_answer);
3071: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3072: [$directory.$new_answer],
3073: [$symb,$env{'request.course.id'},'graded']);
3074: }
3075: }
3076: $$record{$key} = join(',',@versioned_portfiles);
3077: push(@returned_keys,$key);
3078: }
3079: }
3080: return (@returned_keys);
3081: }
3082:
3083: sub get_next_version {
3084: my ($answer_name, $answer_ext, $dir_list) = @_;
3085: my $version;
3086: foreach my $row (@$dir_list) {
3087: my ($file) = split(/\&/,$row,2);
3088: my ($file_name,$file_version,$file_ext) =
3089: &file_name_version_ext($file);
3090: if (($file_name eq $answer_name) &&
3091: ($file_ext eq $answer_ext)) {
3092: # gets here if filename and extension match, regardless of version
3093: if ($file_version ne '') {
3094: # a versioned file is found so save it for later
3095: if ($file_version > $version) {
3096: $version = $file_version;
3097: }
3098: }
3099: }
3100: }
3101: $version ++;
3102: return($version);
3103: }
3104:
3105: sub version_selected_portfile {
3106: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3107: my ($answer_name,$answer_ver,$answer_ext) =
3108: &file_name_version_ext($file_name);
3109: my $new_answer;
3110: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3111: if($env{'form.copy'} eq '-1') {
3112: $new_answer = 'problem getting file';
3113: } else {
3114: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3115: my $copy_result = &Apache::lonnet::finishuserfileupload(
3116: $stu_name,$domain,'copy',
3117: '/portfolio'.$directory.$new_answer);
3118: }
3119: return ($new_answer);
3120: }
3121:
3122: sub file_name_version_ext {
3123: my ($file)=@_;
3124: my @file_parts = split(/\./, $file);
3125: my ($name,$version,$ext);
3126: if (@file_parts > 1) {
3127: $ext=pop(@file_parts);
3128: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3129: $version=pop(@file_parts);
3130: }
3131: $name=join('.',@file_parts);
3132: } else {
3133: $name=join('.',@file_parts);
3134: }
3135: return($name,$version,$ext);
3136: }
3137:
3138: #--------------------------------------------------------------------------------------
3139: #
3140: #-------------------------- Next few routines handles grading by section or whole class
3141: #
3142: #--- Javascript to handle grading by section or whole class
3143: sub viewgrades_js {
3144: my ($request) = shift;
3145:
3146: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3147: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3148: function writePoint(partid,weight,point) {
3149: var radioButton = document.classgrade["RADVAL_"+partid];
3150: var textbox = document.classgrade["TEXTVAL_"+partid];
3151: if (point == "textval") {
3152: point = document.classgrade["TEXTVAL_"+partid].value;
3153: if (isNaN(point) || parseFloat(point) < 0) {
3154: alert("$alertmsg"+parseFloat(point));
3155: var resetbox = false;
3156: for (var i=0; i<radioButton.length; i++) {
3157: if (radioButton[i].checked) {
3158: textbox.value = i;
3159: resetbox = true;
3160: }
3161: }
3162: if (!resetbox) {
3163: textbox.value = "";
3164: }
3165: return;
3166: }
3167: if (parseFloat(point) > parseFloat(weight)) {
3168: var resp = confirm("You entered a value ("+parseFloat(point)+
3169: ") greater than the weight for the part. Accept?");
3170: if (resp == false) {
3171: textbox.value = "";
3172: return;
3173: }
3174: }
3175: for (var i=0; i<radioButton.length; i++) {
3176: radioButton[i].checked=false;
3177: if (parseFloat(point) == i) {
3178: radioButton[i].checked=true;
3179: }
3180: }
3181:
3182: } else {
3183: textbox.value = parseFloat(point);
3184: }
3185: for (i=0;i<document.classgrade.total.value;i++) {
3186: var user = document.classgrade["ctr"+i].value;
3187: user = user.replace(new RegExp(':', 'g'),"_");
3188: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3189: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3190: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3191: if (saveval != "correct") {
3192: scorename.value = point;
3193: if (selname[0].selected != true) {
3194: selname[0].selected = true;
3195: }
3196: }
3197: }
3198: document.classgrade["SELVAL_"+partid][0].selected = true;
3199: }
3200:
3201: function writeRadText(partid,weight) {
3202: var selval = document.classgrade["SELVAL_"+partid];
3203: var radioButton = document.classgrade["RADVAL_"+partid];
3204: var override = document.classgrade["FORCE_"+partid].checked;
3205: var textbox = document.classgrade["TEXTVAL_"+partid];
3206: if (selval[1].selected || selval[2].selected) {
3207: for (var i=0; i<radioButton.length; i++) {
3208: radioButton[i].checked=false;
3209:
3210: }
3211: textbox.value = "";
3212:
3213: for (i=0;i<document.classgrade.total.value;i++) {
3214: var user = document.classgrade["ctr"+i].value;
3215: user = user.replace(new RegExp(':', 'g'),"_");
3216: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3217: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3218: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3219: if ((saveval != "correct") || override) {
3220: scorename.value = "";
3221: if (selval[1].selected) {
3222: selname[1].selected = true;
3223: } else {
3224: selname[2].selected = true;
3225: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3226: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3227: }
3228: }
3229: }
3230: } else {
3231: for (i=0;i<document.classgrade.total.value;i++) {
3232: var user = document.classgrade["ctr"+i].value;
3233: user = user.replace(new RegExp(':', 'g'),"_");
3234: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3235: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3236: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3237: if ((saveval != "correct") || override) {
3238: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3239: selname[0].selected = true;
3240: }
3241: }
3242: }
3243: }
3244:
3245: function changeSelect(partid,user) {
3246: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3247: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3248: var point = textbox.value;
3249: var weight = document.classgrade["weight_"+partid].value;
3250:
3251: if (isNaN(point) || parseFloat(point) < 0) {
3252: alert("$alertmsg"+parseFloat(point));
3253: textbox.value = "";
3254: return;
3255: }
3256: if (parseFloat(point) > parseFloat(weight)) {
3257: var resp = confirm("You entered a value ("+parseFloat(point)+
3258: ") greater than the weight of the part. Accept?");
3259: if (resp == false) {
3260: textbox.value = "";
3261: return;
3262: }
3263: }
3264: selval[0].selected = true;
3265: }
3266:
3267: function changeOneScore(partid,user) {
3268: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3269: if (selval[1].selected || selval[2].selected) {
3270: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3271: if (selval[2].selected) {
3272: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3273: }
3274: }
3275: }
3276:
3277: function resetEntry(numpart) {
3278: for (ctpart=0;ctpart<numpart;ctpart++) {
3279: var partid = document.classgrade["partid_"+ctpart].value;
3280: var radioButton = document.classgrade["RADVAL_"+partid];
3281: var textbox = document.classgrade["TEXTVAL_"+partid];
3282: var selval = document.classgrade["SELVAL_"+partid];
3283: for (var i=0; i<radioButton.length; i++) {
3284: radioButton[i].checked=false;
3285:
3286: }
3287: textbox.value = "";
3288: selval[0].selected = true;
3289:
3290: for (i=0;i<document.classgrade.total.value;i++) {
3291: var user = document.classgrade["ctr"+i].value;
3292: user = user.replace(new RegExp(':', 'g'),"_");
3293: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3294: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3295: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3296: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3297: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3298: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3299: if (saveselval == "excused") {
3300: if (selname[1].selected == false) { selname[1].selected = true;}
3301: } else {
3302: if (selname[0].selected == false) {selname[0].selected = true};
3303: }
3304: }
3305: }
3306: }
3307:
3308: VIEWJAVASCRIPT
3309: }
3310:
3311: #--- show scores for a section or whole class w/ option to change/update a score
3312: sub viewgrades {
3313: my ($request,$symb) = @_;
3314: &viewgrades_js($request);
3315:
3316: #need to make sure we have the correct data for later EXT calls,
3317: #thus invalidate the cache
3318: &Apache::lonnet::devalidatecourseresdata(
3319: $env{'course.'.$env{'request.course.id'}.'.num'},
3320: $env{'course.'.$env{'request.course.id'}.'.domain'});
3321: &Apache::lonnet::clear_EXT_cache_status();
3322:
3323: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3324:
3325: #view individual student submission form - called using Javascript viewOneStudent
3326: $result.=&jscriptNform($symb);
3327:
3328: #beginning of class grading form
3329: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3330: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3331: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3332: '<input type="hidden" name="command" value="editgrades" />'."\n".
3333: &build_section_inputs().
3334: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3335:
3336: my ($common_header,$specific_header);
3337: if ($env{'form.section'} eq 'all') {
3338: $common_header = &mt('Assign Common Grade to Class');
3339: $specific_header = &mt('Assign Grade to Specific Students in Class');
3340: } elsif ($env{'form.section'} eq 'none') {
3341: $common_header = &mt('Assign Common Grade to Students in no Section');
3342: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3343: } else {
3344: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3345: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3346: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3347: }
3348: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3349: #radio buttons/text box for assigning points for a section or class.
3350: #handles different parts of a problem
3351: my $res_error;
3352: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3353: if ($res_error) {
3354: return &navmap_errormsg();
3355: }
3356: my %weight = ();
3357: my $ctsparts = 0;
3358: my %seen = ();
3359: my @part_response_id = &flatten_responseType($responseType);
3360: foreach my $part_response_id (@part_response_id) {
3361: my ($partid,$respid) = @{ $part_response_id };
3362: my $part_resp = join('_',@{ $part_response_id });
3363: next if $seen{$partid};
3364: $seen{$partid}++;
3365: my $handgrade=$$handgrade{$part_resp};
3366: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3367: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3368:
3369: my $display_part=&get_display_part($partid,$symb);
3370: my $radio.='<table border="0"><tr>';
3371: my $ctr = 0;
3372: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3373: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3374: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3375: ','.$ctr.')" />'.$ctr."</label></td>\n";
3376: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3377: $ctr++;
3378: }
3379: $radio.='</tr></table>';
3380: my $line = '<input type="text" name="TEXTVAL_'.
3381: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3382: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3383: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3384: $line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
3385: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3386: $weight{$partid}.')"> '.
3387: '<option selected="selected"> </option>'.
3388: '<option value="excused">'.&mt('excused').'</option>'.
3389: '<option value="reset status">'.&mt('reset status').'</option>'.
3390: '</select></td>'.
3391: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3392: $line.='<input type="hidden" name="partid_'.
3393: $ctsparts.'" value="'.$partid.'" />'."\n";
3394: $line.='<input type="hidden" name="weight_'.
3395: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3396:
3397: $result.=
3398: &Apache::loncommon::start_data_table_row()."\n".
3399: '<td><b>'.&mt('Part:').'</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points:').'</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>'.
3400: &Apache::loncommon::end_data_table_row()."\n";
3401: $ctsparts++;
3402: }
3403: $result.=&Apache::loncommon::end_data_table()."\n".
3404: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3405: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3406: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3407:
3408: #table listing all the students in a section/class
3409: #header of table
3410: $result.= '<h3>'.$specific_header.'</h3>'.
3411: &Apache::loncommon::start_data_table().
3412: &Apache::loncommon::start_data_table_header_row().
3413: '<th>'.&mt('No.').'</th>'.
3414: '<th>'.&nameUserString('header')."</th>\n";
3415: my $partserror;
3416: my (@parts) = sort(&getpartlist($symb,\$partserror));
3417: if ($partserror) {
3418: return &navmap_errormsg();
3419: }
3420: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3421: my @partids = ();
3422: foreach my $part (@parts) {
3423: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3424: my $narrowtext = &mt('Tries');
3425: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3426: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3427: my ($partid) = &split_part_type($part);
3428: push(@partids,$partid);
3429: #
3430: # FIXME: Looks like $display looks at English text
3431: #
3432: my $display_part=&get_display_part($partid,$symb);
3433: if ($display =~ /^Partial Credit Factor/) {
3434: $result.='<th>'.
3435: &mt('Score Part: [_1]<br /> (weight = [_2])',
3436: $display_part,$weight{$partid}).'</th>'."\n";
3437: next;
3438:
3439: } else {
3440: if ($display =~ /Problem Status/) {
3441: my $grade_status_mt = &mt('Grade Status');
3442: $display =~ s{Problem Status}{$grade_status_mt<br />};
3443: }
3444: my $part_mt = &mt('Part:');
3445: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3446: }
3447:
3448: $result.='<th>'.$display.'</th>'."\n";
3449: }
3450: $result.=&Apache::loncommon::end_data_table_header_row();
3451:
3452: my %last_resets =
3453: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3454:
3455: #get info for each student
3456: #list all the students - with points and grade status
3457: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3458: my $ctr = 0;
3459: foreach (sort
3460: {
3461: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3462: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3463: }
3464: return $a cmp $b;
3465: } (keys(%$fullname))) {
3466: $ctr++;
3467: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3468: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3469: }
3470: $result.=&Apache::loncommon::end_data_table();
3471: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3472: $result.='<input type="button" value="'.&mt('Save').'" '.
3473: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3474: if (scalar(%$fullname) eq 0) {
3475: my $colspan=3+scalar(@parts);
3476: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3477: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3478: $result='<span class="LC_warning">'.
3479: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3480: $section_display, $stu_status).
3481: '</span>';
3482: }
3483: return $result;
3484: }
3485:
3486: #--- call by previous routine to display each student
3487: sub viewstudentgrade {
3488: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3489: my ($uname,$udom) = split(/:/,$student);
3490: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3491: my %aggregates = ();
3492: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3493: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3494: "\n".$ctr.' </td><td> '.
3495: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3496: '\');" target="_self">'.$fullname.'</a> '.
3497: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3498: $student=~s/:/_/; # colon doen't work in javascript for names
3499: foreach my $apart (@$parts) {
3500: my ($part,$type) = &split_part_type($apart);
3501: my $score=$record{"resource.$part.$type"};
3502: $result.='<td align="center">';
3503: my ($aggtries,$totaltries);
3504: unless (exists($aggregates{$part})) {
3505: $totaltries = $record{'resource.'.$part.'.tries'};
3506:
3507: $aggtries = $totaltries;
3508: if ($$last_resets{$part}) {
3509: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3510: $part);
3511: }
3512: $result.='<input type="hidden" name="'.
3513: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3514: $result.='<input type="hidden" name="'.
3515: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3516: $aggregates{$part} = 1;
3517: }
3518: if ($type eq 'awarded') {
3519: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3520: $result.='<input type="hidden" name="'.
3521: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3522: $result.='<input type="text" name="'.
3523: 'GD_'.$student.'_'.$part.'_awarded" '.
3524: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3525: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3526: } elsif ($type eq 'solved') {
3527: my ($status,$foo)=split(/_/,$score,2);
3528: $status = 'nothing' if ($status eq '');
3529: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3530: $part.'_solved_s" value="'.$status.'" />'."\n";
3531: $result.=' <select name="'.
3532: 'GD_'.$student.'_'.$part.'_solved" '.
3533: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3534: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3535: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3536: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3537: $result.="</select> </td>\n";
3538: } else {
3539: $result.='<input type="hidden" name="'.
3540: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3541: "\n";
3542: $result.='<input type="text" name="'.
3543: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3544: 'value="'.$score.'" size="4" /></td>'."\n";
3545: }
3546: }
3547: $result.=&Apache::loncommon::end_data_table_row();
3548: return $result;
3549: }
3550:
3551: #--- change scores for all the students in a section/class
3552: # record does not get update if unchanged
3553: sub editgrades {
3554: my ($request,$symb) = @_;
3555:
3556: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3557: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3558: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3559:
3560: my $result= &Apache::loncommon::start_data_table().
3561: &Apache::loncommon::start_data_table_header_row().
3562: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3563: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3564: my %scoreptr = (
3565: 'correct' =>'correct_by_override',
3566: 'incorrect'=>'incorrect_by_override',
3567: 'excused' =>'excused',
3568: 'ungraded' =>'ungraded_attempted',
3569: 'credited' =>'credit_attempted',
3570: 'nothing' => '',
3571: );
3572: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3573:
3574: my (@partid);
3575: my %weight = ();
3576: my %columns = ();
3577: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3578:
3579: my $partserror;
3580: my (@parts) = sort(&getpartlist($symb,\$partserror));
3581: if ($partserror) {
3582: return &navmap_errormsg();
3583: }
3584: my $header;
3585: while ($ctr < $env{'form.totalparts'}) {
3586: my $partid = $env{'form.partid_'.$ctr};
3587: push(@partid,$partid);
3588: $weight{$partid} = $env{'form.weight_'.$partid};
3589: $ctr++;
3590: }
3591: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3592: foreach my $partid (@partid) {
3593: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3594: '<th align="center">'.&mt('New Score').'</th>';
3595: $columns{$partid}=2;
3596: foreach my $stores (@parts) {
3597: my ($part,$type) = &split_part_type($stores);
3598: if ($part !~ m/^\Q$partid\E/) { next;}
3599: if ($type eq 'awarded' || $type eq 'solved') { next; }
3600: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3601: $display =~ s/\[Part: \Q$part\E\]//;
3602: my $narrowtext = &mt('Tries');
3603: $display =~ s/Number of Attempts/$narrowtext/;
3604: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3605: '<th align="center">'.&mt('New').' '.$display.'</th>';
3606: $columns{$partid}+=2;
3607: }
3608: }
3609: foreach my $partid (@partid) {
3610: my $display_part=&get_display_part($partid,$symb);
3611: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3612: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3613: '</th>';
3614:
3615: }
3616: $result .= &Apache::loncommon::end_data_table_header_row().
3617: &Apache::loncommon::start_data_table_header_row().
3618: $header.
3619: &Apache::loncommon::end_data_table_header_row();
3620: my @noupdate;
3621: my ($updateCtr,$noupdateCtr) = (1,1);
3622: for ($i=0; $i<$env{'form.total'}; $i++) {
3623: my $line;
3624: my $user = $env{'form.ctr'.$i};
3625: my ($uname,$udom)=split(/:/,$user);
3626: my %newrecord;
3627: my $updateflag = 0;
3628: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3629: my $usec=$classlist->{"$uname:$udom"}[5];
3630: if (!&canmodify($usec)) {
3631: my $numcols=scalar(@partid)*4+2;
3632: push(@noupdate,
3633: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3634: &mt('Not allowed to modify student')."</span></td></tr>");
3635: next;
3636: }
3637: my %aggregate = ();
3638: my $aggregateflag = 0;
3639: $user=~s/:/_/; # colon doen't work in javascript for names
3640: foreach (@partid) {
3641: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3642: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3643: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3644: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3645: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3646: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3647: my $partial = $awarded eq '' ? '' : $pcr;
3648: my $score;
3649: if ($partial eq '') {
3650: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3651: } elsif ($partial > 0) {
3652: $score = 'correct_by_override';
3653: } elsif ($partial == 0) {
3654: $score = 'incorrect_by_override';
3655: }
3656: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3657: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3658:
3659: $newrecord{'resource.'.$_.'.regrader'}=
3660: "$env{'user.name'}:$env{'user.domain'}";
3661: if ($dropMenu eq 'reset status' &&
3662: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3663: $newrecord{'resource.'.$_.'.tries'} = '';
3664: $newrecord{'resource.'.$_.'.solved'} = '';
3665: $newrecord{'resource.'.$_.'.award'} = '';
3666: $newrecord{'resource.'.$_.'.awarded'} = '';
3667: $updateflag = 1;
3668: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3669: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3670: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3671: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3672: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3673: $aggregateflag = 1;
3674: }
3675: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3676: $updateflag = 1;
3677: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3678: $newrecord{'resource.'.$_.'.solved'} = $score;
3679: $rec_update++;
3680: }
3681:
3682: $line .= '<td align="center">'.$old_aw.' </td>'.
3683: '<td align="center">'.$awarded.
3684: ($score eq 'excused' ? $score : '').' </td>';
3685:
3686:
3687: my $partid=$_;
3688: foreach my $stores (@parts) {
3689: my ($part,$type) = &split_part_type($stores);
3690: if ($part !~ m/^\Q$partid\E/) { next;}
3691: if ($type eq 'awarded' || $type eq 'solved') { next; }
3692: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3693: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3694: if ($awarded ne '' && $awarded ne $old_aw) {
3695: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3696: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3697: $updateflag=1;
3698: }
3699: $line .= '<td align="center">'.$old_aw.' </td>'.
3700: '<td align="center">'.$awarded.' </td>';
3701: }
3702: }
3703: $line.="\n";
3704:
3705: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3706: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3707:
3708: if ($updateflag) {
3709: $count++;
3710: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3711: $udom,$uname);
3712:
3713: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3714: $cnum,$udom,$uname)) {
3715: # need to figure out if should be in queue.
3716: my %record =
3717: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3718: $udom,$uname);
3719: my $all_graded = 1;
3720: my $none_graded = 1;
3721: foreach my $part (@parts) {
3722: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3723: $all_graded = 0;
3724: } else {
3725: $none_graded = 0;
3726: }
3727: }
3728:
3729: if ($all_graded || $none_graded) {
3730: &Apache::bridgetask::remove_from_queue('gradingqueue',
3731: $symb,$cdom,$cnum,
3732: $udom,$uname);
3733: }
3734: }
3735:
3736: $result.=&Apache::loncommon::start_data_table_row().
3737: '<td align="right"> '.$updateCtr.' </td>'.$line.
3738: &Apache::loncommon::end_data_table_row();
3739: $updateCtr++;
3740: } else {
3741: push(@noupdate,
3742: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3743: $noupdateCtr++;
3744: }
3745: if ($aggregateflag) {
3746: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3747: $cdom,$cnum);
3748: }
3749: }
3750: if (@noupdate) {
3751: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3752: my $numcols=scalar(@partid)*4+2;
3753: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3754: '<td align="center" colspan="'.$numcols.'">'.
3755: &mt('No Changes Occurred For the Students Below').
3756: '</td>'.
3757: &Apache::loncommon::end_data_table_row();
3758: foreach my $line (@noupdate) {
3759: $result.=
3760: &Apache::loncommon::start_data_table_row().
3761: $line.
3762: &Apache::loncommon::end_data_table_row();
3763: }
3764: }
3765: $result .= &Apache::loncommon::end_data_table();
3766: my $msg = '<p><b>'.
3767: &mt('Number of records updated = [_1] for [quant,_2,student].',
3768: $rec_update,$count).'</b><br />'.
3769: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3770: '</b></p>';
3771: return $title.$msg.$result;
3772: }
3773:
3774: sub split_part_type {
3775: my ($partstr) = @_;
3776: my ($temp,@allparts)=split(/_/,$partstr);
3777: my $type=pop(@allparts);
3778: my $part=join('_',@allparts);
3779: return ($part,$type);
3780: }
3781:
3782: #------------- end of section for handling grading by section/class ---------
3783: #
3784: #----------------------------------------------------------------------------
3785:
3786:
3787: #----------------------------------------------------------------------------
3788: #
3789: #-------------------------- Next few routines handles grading by csv upload
3790: #
3791: #--- Javascript to handle csv upload
3792: sub csvupload_javascript_reverse_associate {
3793: my $error1=&mt('You need to specify the username or the student/employee ID');
3794: my $error2=&mt('You need to specify at least one grading field');
3795: return(<<ENDPICK);
3796: function verify(vf) {
3797: var foundsomething=0;
3798: var founduname=0;
3799: var foundID=0;
3800: for (i=0;i<=vf.nfields.value;i++) {
3801: tw=eval('vf.f'+i+'.selectedIndex');
3802: if (i==0 && tw!=0) { foundID=1; }
3803: if (i==1 && tw!=0) { founduname=1; }
3804: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3805: }
3806: if (founduname==0 && foundID==0) {
3807: alert('$error1');
3808: return;
3809: }
3810: if (foundsomething==0) {
3811: alert('$error2');
3812: return;
3813: }
3814: vf.submit();
3815: }
3816: function flip(vf,tf) {
3817: var nw=eval('vf.f'+tf+'.selectedIndex');
3818: var i;
3819: for (i=0;i<=vf.nfields.value;i++) {
3820: //can not pick the same destination field for both name and domain
3821: if (((i ==0)||(i ==1)) &&
3822: ((tf==0)||(tf==1)) &&
3823: (i!=tf) &&
3824: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3825: eval('vf.f'+i+'.selectedIndex=0;')
3826: }
3827: }
3828: }
3829: ENDPICK
3830: }
3831:
3832: sub csvupload_javascript_forward_associate {
3833: my $error1=&mt('You need to specify the username or the student/employee ID');
3834: my $error2=&mt('You need to specify at least one grading field');
3835: return(<<ENDPICK);
3836: function verify(vf) {
3837: var foundsomething=0;
3838: var founduname=0;
3839: var foundID=0;
3840: for (i=0;i<=vf.nfields.value;i++) {
3841: tw=eval('vf.f'+i+'.selectedIndex');
3842: if (tw==1) { foundID=1; }
3843: if (tw==2) { founduname=1; }
3844: if (tw>3) { foundsomething=1; }
3845: }
3846: if (founduname==0 && foundID==0) {
3847: alert('$error1');
3848: return;
3849: }
3850: if (foundsomething==0) {
3851: alert('$error2');
3852: return;
3853: }
3854: vf.submit();
3855: }
3856: function flip(vf,tf) {
3857: var nw=eval('vf.f'+tf+'.selectedIndex');
3858: var i;
3859: //can not pick the same destination field twice
3860: for (i=0;i<=vf.nfields.value;i++) {
3861: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3862: eval('vf.f'+i+'.selectedIndex=0;')
3863: }
3864: }
3865: }
3866: ENDPICK
3867: }
3868:
3869: sub csvuploadmap_header {
3870: my ($request,$symb,$datatoken,$distotal)= @_;
3871: my $javascript;
3872: if ($env{'form.upfile_associate'} eq 'reverse') {
3873: $javascript=&csvupload_javascript_reverse_associate();
3874: } else {
3875: $javascript=&csvupload_javascript_forward_associate();
3876: }
3877:
3878: $symb = &Apache::lonenc::check_encrypt($symb);
3879: $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
3880: &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
3881: &mt('Associate entries from the uploaded file with as many fields as you can.'));
3882: my $reverse=&mt("Reverse Association");
3883: $request->print(<<ENDPICK);
3884: <br />
3885: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3886: <input type="hidden" name="associate" value="" />
3887: <input type="hidden" name="phase" value="three" />
3888: <input type="hidden" name="datatoken" value="$datatoken" />
3889: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3890: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3891: <input type="hidden" name="upfile_associate"
3892: value="$env{'form.upfile_associate'}" />
3893: <input type="hidden" name="symb" value="$symb" />
3894: <input type="hidden" name="command" value="csvuploadoptions" />
3895: <hr />
3896: ENDPICK
3897: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
3898: return '';
3899:
3900: }
3901:
3902: sub csvupload_fields {
3903: my ($symb,$errorref) = @_;
3904: my (@parts) = &getpartlist($symb,$errorref);
3905: if (ref($errorref)) {
3906: if ($$errorref) {
3907: return;
3908: }
3909: }
3910:
3911: my @fields=(['ID','Student/Employee ID'],
3912: ['username','Student Username'],
3913: ['domain','Student Domain']);
3914: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3915: foreach my $part (sort(@parts)) {
3916: my @datum;
3917: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3918: my $name=$part;
3919: if (!$display) { $display = $name; }
3920: @datum=($name,$display);
3921: if ($name=~/^stores_(.*)_awarded/) {
3922: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3923: }
3924: push(@fields,\@datum);
3925: }
3926: return (@fields);
3927: }
3928:
3929: sub csvuploadmap_footer {
3930: my ($request,$i,$keyfields) =@_;
3931: $request->print(<<ENDPICK);
3932: </table>
3933: <input type="hidden" name="nfields" value="$i" />
3934: <input type="hidden" name="keyfields" value="$keyfields" />
3935: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
3936: </form>
3937: ENDPICK
3938: }
3939:
3940: sub checkforfile_js {
3941: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
3942: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
3943: function checkUpload(formname) {
3944: if (formname.upfile.value == "") {
3945: alert("$alertmsg");
3946: return false;
3947: }
3948: formname.submit();
3949: }
3950: CSVFORMJS
3951: return $result;
3952: }
3953:
3954: sub upcsvScores_form {
3955: my ($request,$symb) = @_;
3956: if (!$symb) {return '';}
3957: my $result=&checkforfile_js();
3958: $result.=&Apache::loncommon::start_data_table().
3959: &Apache::loncommon::start_data_table_header_row().
3960: '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
3961: &Apache::loncommon::end_data_table_header_row().
3962: &Apache::loncommon::start_data_table_row().'<td>';
3963: my $upload=&mt("Upload Scores");
3964: my $upfile_select=&Apache::loncommon::upfile_select_html();
3965: my $ignore=&mt('Ignore First Line');
3966: $symb = &Apache::lonenc::check_encrypt($symb);
3967: $result.=<<ENDUPFORM;
3968: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3969: <input type="hidden" name="symb" value="$symb" />
3970: <input type="hidden" name="command" value="csvuploadmap" />
3971: $upfile_select
3972: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
3973: </form>
3974: ENDUPFORM
3975: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3976: &mt("How do I create a CSV file from a spreadsheet")).
3977: '</td>'.
3978: &Apache::loncommon::end_data_table_row().
3979: &Apache::loncommon::end_data_table();
3980: return $result;
3981: }
3982:
3983:
3984: sub csvuploadmap {
3985: my ($request,$symb)= @_;
3986: if (!$symb) {return '';}
3987:
3988: my $datatoken;
3989: if (!$env{'form.datatoken'}) {
3990: $datatoken=&Apache::loncommon::upfile_store($request);
3991: } else {
3992: $datatoken=$env{'form.datatoken'};
3993: &Apache::loncommon::load_tmp_file($request);
3994: }
3995: my @records=&Apache::loncommon::upfile_record_sep();
3996: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3997: my ($i,$keyfields);
3998: if (@records) {
3999: my $fieldserror;
4000: my @fields=&csvupload_fields($symb,\$fieldserror);
4001: if ($fieldserror) {
4002: $request->print(&navmap_errormsg());
4003: return;
4004: }
4005: if ($env{'form.upfile_associate'} eq 'reverse') {
4006: &Apache::loncommon::csv_print_samples($request,\@records);
4007: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4008: \@fields);
4009: foreach (@fields) { $keyfields.=$_->[0].','; }
4010: chop($keyfields);
4011: } else {
4012: unshift(@fields,['none','']);
4013: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4014: \@fields);
4015: foreach my $rec (@records) {
4016: my %temp = &Apache::loncommon::record_sep($rec);
4017: if (%temp) {
4018: $keyfields=join(',',sort(keys(%temp)));
4019: last;
4020: }
4021: }
4022: }
4023: }
4024: &csvuploadmap_footer($request,$i,$keyfields);
4025:
4026: return '';
4027: }
4028:
4029: sub csvuploadoptions {
4030: my ($request,$symb)= @_;
4031: my $overwrite=&mt('Overwrite any existing score');
4032: $request->print(<<ENDPICK);
4033: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4034: <input type="hidden" name="command" value="csvuploadassign" />
4035: <p>
4036: <label>
4037: <input type="checkbox" name="overwite_scores" checked="checked" />
4038: $overwrite
4039: </label>
4040: </p>
4041: ENDPICK
4042: my %fields=&get_fields();
4043: if (!defined($fields{'domain'})) {
4044: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4045: $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
4046: }
4047: foreach my $key (sort(keys(%env))) {
4048: if ($key !~ /^form\.(.*)$/) { next; }
4049: my $cleankey=$1;
4050: if ($cleankey eq 'command') { next; }
4051: $request->print('<input type="hidden" name="'.$cleankey.
4052: '" value="'.$env{$key}.'" />'."\n");
4053: }
4054: # FIXME do a check for any duplicated user ids...
4055: # FIXME do a check for any invalid user ids?...
4056: $request->print('<input type="submit" value="Assign Grades" /><br />
4057: <hr /></form>'."\n");
4058: return '';
4059: }
4060:
4061: sub get_fields {
4062: my %fields;
4063: my @keyfields = split(/\,/,$env{'form.keyfields'});
4064: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4065: if ($env{'form.upfile_associate'} eq 'reverse') {
4066: if ($env{'form.f'.$i} ne 'none') {
4067: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4068: }
4069: } else {
4070: if ($env{'form.f'.$i} ne 'none') {
4071: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4072: }
4073: }
4074: }
4075: return %fields;
4076: }
4077:
4078: sub csvuploadassign {
4079: my ($request,$symb)= @_;
4080: if (!$symb) {return '';}
4081: my $error_msg = '';
4082: &Apache::loncommon::load_tmp_file($request);
4083: my @gradedata = &Apache::loncommon::upfile_record_sep();
4084: my %fields=&get_fields();
4085: my $courseid=$env{'request.course.id'};
4086: my ($classlist) = &getclasslist('all',0);
4087: my @notallowed;
4088: my @skipped;
4089: my $countdone=0;
4090: foreach my $grade (@gradedata) {
4091: my %entries=&Apache::loncommon::record_sep($grade);
4092: my $domain;
4093: if ($entries{$fields{'domain'}}) {
4094: $domain=$entries{$fields{'domain'}};
4095: } else {
4096: $domain=$env{'form.default_domain'};
4097: }
4098: $domain=~s/\s//g;
4099: my $username=$entries{$fields{'username'}};
4100: $username=~s/\s//g;
4101: if (!$username) {
4102: my $id=$entries{$fields{'ID'}};
4103: $id=~s/\s//g;
4104: my %ids=&Apache::lonnet::idget($domain,$id);
4105: $username=$ids{$id};
4106: }
4107: if (!exists($$classlist{"$username:$domain"})) {
4108: my $id=$entries{$fields{'ID'}};
4109: $id=~s/\s//g;
4110: if ($id) {
4111: push(@skipped,"$id:$domain");
4112: } else {
4113: push(@skipped,"$username:$domain");
4114: }
4115: next;
4116: }
4117: my $usec=$classlist->{"$username:$domain"}[5];
4118: if (!&canmodify($usec)) {
4119: push(@notallowed,"$username:$domain");
4120: next;
4121: }
4122: my %points;
4123: my %grades;
4124: foreach my $dest (keys(%fields)) {
4125: if ($dest eq 'ID' || $dest eq 'username' ||
4126: $dest eq 'domain') { next; }
4127: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4128: if ($dest=~/stores_(.*)_points/) {
4129: my $part=$1;
4130: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4131: $symb,$domain,$username);
4132: if ($wgt) {
4133: $entries{$fields{$dest}}=~s/\s//g;
4134: my $pcr=$entries{$fields{$dest}} / $wgt;
4135: my $award=($pcr == 0) ? 'incorrect_by_override'
4136: : 'correct_by_override';
4137: if ($pcr>1) {
4138: push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
4139: }
4140: $grades{"resource.$part.awarded"}=$pcr;
4141: $grades{"resource.$part.solved"}=$award;
4142: $points{$part}=1;
4143: } else {
4144: $error_msg = "<br />" .
4145: &mt("Some point values were assigned"
4146: ." for problems with a weight "
4147: ."of zero. These values were "
4148: ."ignored.");
4149: }
4150: } else {
4151: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4152: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4153: my $store_key=$dest;
4154: $store_key=~s/^stores/resource/;
4155: $store_key=~s/_/\./g;
4156: $grades{$store_key}=$entries{$fields{$dest}};
4157: }
4158: }
4159: if (! %grades) {
4160: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4161: } else {
4162: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4163: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4164: $env{'request.course.id'},
4165: $domain,$username);
4166: if ($result eq 'ok') {
4167: # Successfully stored
4168: $request->print('.');
4169: # Remove from grading queue
4170: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4171: $env{'course.'.$env{'request.course.id'}.'.domain'},
4172: $env{'course.'.$env{'request.course.id'}.'.num'},
4173: $domain,$username);
4174: $countdone++;
4175: } else {
4176: $request->print("<p><span class=\"LC_error\">".
4177: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4178: "$username:$domain",$result)."</span></p>");
4179: }
4180: $request->rflush();
4181: }
4182: }
4183: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4184: if (@skipped) {
4185: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4186: $request->print(join(', ',@skipped));
4187: }
4188: if (@notallowed) {
4189: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4190: $request->print(join(', ',@notallowed));
4191: }
4192: $request->print("<br />\n");
4193: return $error_msg;
4194: }
4195: #------------- end of section for handling csv file upload ---------
4196: #
4197: #-------------------------------------------------------------------
4198: #
4199: #-------------- Next few routines handle grading by page/sequence
4200: #
4201: #--- Select a page/sequence and a student to grade
4202: sub pickStudentPage {
4203: my ($request,$symb) = @_;
4204:
4205: my $alertmsg = &mt('Please select the student you wish to grade.');
4206: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4207:
4208: function checkPickOne(formname) {
4209: if (radioSelection(formname.student) == null) {
4210: alert("$alertmsg");
4211: return;
4212: }
4213: ptr = pullDownSelection(formname.selectpage);
4214: formname.page.value = formname["page"+ptr].value;
4215: formname.title.value = formname["title"+ptr].value;
4216: formname.submit();
4217: }
4218:
4219: LISTJAVASCRIPT
4220: &commonJSfunctions($request);
4221:
4222: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4223: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4224: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4225:
4226: my $result='<h3><span class="LC_info"> '.
4227: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4228:
4229: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4230: my $map_error;
4231: my ($titles,$symbx) = &getSymbMap($map_error);
4232: if ($map_error) {
4233: $request->print(&navmap_errormsg());
4234: return;
4235: }
4236: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4237: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4238: # my $type=($curpage =~ /\.(page|sequence)/);
4239: my $select = '<select name="selectpage">'."\n";
4240: my $ctr=0;
4241: foreach (@$titles) {
4242: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4243: $select.='<option value="'.$ctr.'" '.
4244: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4245: '>'.$showtitle.'</option>'."\n";
4246: $ctr++;
4247: }
4248: $select.= '</select>';
4249: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4250:
4251: $ctr=0;
4252: foreach (@$titles) {
4253: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4254: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4255: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4256: $ctr++;
4257: }
4258: $result.='<input type="hidden" name="page" />'."\n".
4259: '<input type="hidden" name="title" />'."\n";
4260:
4261: my $options =
4262: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4263: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4264: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4265:
4266: $options =
4267: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4268: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4269: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4270: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4271:
4272: $result.=&build_section_inputs();
4273: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4274: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4275: '<input type="hidden" name="command" value="displayPage" />'."\n".
4276: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
4277:
4278: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4279:
4280: $result.=' <input type="button" '.
4281: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4282:
4283: $request->print($result);
4284:
4285: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4286: &Apache::loncommon::start_data_table().
4287: &Apache::loncommon::start_data_table_header_row().
4288: '<th align="right"> '.&mt('No.').'</th>'.
4289: '<th>'.&nameUserString('header').'</th>'.
4290: '<th align="right"> '.&mt('No.').'</th>'.
4291: '<th>'.&nameUserString('header').'</th>'.
4292: &Apache::loncommon::end_data_table_header_row();
4293:
4294: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4295: my $ptr = 1;
4296: foreach my $student (sort
4297: {
4298: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4299: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4300: }
4301: return $a cmp $b;
4302: } (keys(%$fullname))) {
4303: my ($uname,$udom) = split(/:/,$student);
4304: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4305: : '</td>');
4306: $studentTable.='<td align="right">'.$ptr.' </td>';
4307: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4308: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4309: $studentTable.=
4310: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4311: : '');
4312: $ptr++;
4313: }
4314: if ($ptr%2 == 0) {
4315: $studentTable.='</td><td> </td><td> </td>'.
4316: &Apache::loncommon::end_data_table_row();
4317: }
4318: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4319: $studentTable.='<input type="button" '.
4320: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4321:
4322: $request->print($studentTable);
4323:
4324: return '';
4325: }
4326:
4327: sub getSymbMap {
4328: my ($map_error) = @_;
4329: my $navmap = Apache::lonnavmaps::navmap->new();
4330: unless (ref($navmap)) {
4331: if (ref($map_error)) {
4332: $$map_error = 'navmap';
4333: }
4334: return;
4335: }
4336: my %symbx = ();
4337: my @titles = ();
4338: my $minder = 0;
4339:
4340: # Gather every sequence that has problems.
4341: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4342: 1,0,1);
4343: for my $sequence ($navmap->getById('0.0'), @sequences) {
4344: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4345: my $title = $minder.'.'.
4346: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4347: push(@titles, $title); # minder in case two titles are identical
4348: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4349: $minder++;
4350: }
4351: }
4352: return \@titles,\%symbx;
4353: }
4354:
4355: #
4356: #--- Displays a page/sequence w/wo problems, w/wo submissions
4357: sub displayPage {
4358: my ($request,$symb) = @_;
4359: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4360: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4361: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4362: my $pageTitle = $env{'form.page'};
4363: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4364: my ($uname,$udom) = split(/:/,$env{'form.student'});
4365: my $usec=$classlist->{$env{'form.student'}}[5];
4366:
4367: #need to make sure we have the correct data for later EXT calls,
4368: #thus invalidate the cache
4369: &Apache::lonnet::devalidatecourseresdata(
4370: $env{'course.'.$env{'request.course.id'}.'.num'},
4371: $env{'course.'.$env{'request.course.id'}.'.domain'});
4372: &Apache::lonnet::clear_EXT_cache_status();
4373:
4374: if (!&canview($usec)) {
4375: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4376: return;
4377: }
4378: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4379: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4380: '</h3>'."\n";
4381: $env{'form.CODE'} = uc($env{'form.CODE'});
4382: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4383: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4384: } else {
4385: delete($env{'form.CODE'});
4386: }
4387: &sub_page_js($request);
4388: $request->print($result);
4389:
4390: my $navmap = Apache::lonnavmaps::navmap->new();
4391: unless (ref($navmap)) {
4392: $request->print(&navmap_errormsg());
4393: return;
4394: }
4395: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4396: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4397: if (!$map) {
4398: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4399: return;
4400: }
4401: my $iterator = $navmap->getIterator($map->map_start(),
4402: $map->map_finish());
4403:
4404: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4405: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4406: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4407: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4408: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4409: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4410: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4411: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4412:
4413: if (defined($env{'form.CODE'})) {
4414: $studentTable.=
4415: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4416: }
4417: my $checkIcon = '<img alt="'.&mt('Check Mark').
4418: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4419:
4420: $studentTable.=' <span class="LC_info">'.
4421: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4422: '</span>'."\n".
4423: &Apache::loncommon::start_data_table().
4424: &Apache::loncommon::start_data_table_header_row().
4425: '<th align="center"> Prob. </th>'.
4426: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4427: &Apache::loncommon::end_data_table_header_row();
4428:
4429: &Apache::lonxml::clear_problem_counter();
4430: my ($depth,$question,$prob) = (1,1,1);
4431: $iterator->next(); # skip the first BEGIN_MAP
4432: my $curRes = $iterator->next(); # for "current resource"
4433: while ($depth > 0) {
4434: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4435: if($curRes == $iterator->END_MAP) { $depth--; }
4436:
4437: if (ref($curRes) && $curRes->is_problem()) {
4438: my $parts = $curRes->parts();
4439: my $title = $curRes->compTitle();
4440: my $symbx = $curRes->symb();
4441: $studentTable.=
4442: &Apache::loncommon::start_data_table_row().
4443: '<td align="center" valign="top" >'.$prob.
4444: (scalar(@{$parts}) == 1 ? ''
4445: : '<br />('.&mt('[_1]parts)',
4446: scalar(@{$parts}).' ')
4447: ).
4448: '</td>';
4449: $studentTable.='<td valign="top">';
4450: my %form = ('CODE' => $env{'form.CODE'},);
4451: if ($env{'form.vProb'} eq 'yes' ) {
4452: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4453: undef,'both',\%form);
4454: } else {
4455: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4456: $companswer =~ s|<form(.*?)>||g;
4457: $companswer =~ s|</form>||g;
4458: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4459: # $companswer =~ s/$1/ /ms;
4460: # $request->print('match='.$1."<br />\n");
4461: # }
4462: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4463: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4464: }
4465:
4466: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4467:
4468: if ($env{'form.lastSub'} eq 'datesub') {
4469: if ($record{'version'} eq '') {
4470: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4471: } else {
4472: my %responseType = ();
4473: foreach my $partid (@{$parts}) {
4474: my @responseIds =$curRes->responseIds($partid);
4475: my @responseType =$curRes->responseType($partid);
4476: my %responseIds;
4477: for (my $i=0;$i<=$#responseIds;$i++) {
4478: $responseIds{$responseIds[$i]}=$responseType[$i];
4479: }
4480: $responseType{$partid} = \%responseIds;
4481: }
4482: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4483:
4484: }
4485: } elsif ($env{'form.lastSub'} eq 'all') {
4486: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4487: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4488: $env{'request.course.id'},
4489: '','.submission');
4490:
4491: }
4492: if (&canmodify($usec)) {
4493: $studentTable.=&gradeBox_start();
4494: foreach my $partid (@{$parts}) {
4495: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4496: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4497: $question++;
4498: }
4499: $studentTable.=&gradeBox_end();
4500: $prob++;
4501: }
4502: $studentTable.='</td></tr>';
4503:
4504: }
4505: $curRes = $iterator->next();
4506: }
4507:
4508: $studentTable.=
4509: '</table>'."\n".
4510: '<input type="button" value="'.&mt('Save').'" '.
4511: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4512: '</form>'."\n";
4513: $request->print($studentTable);
4514:
4515: return '';
4516: }
4517:
4518: sub displaySubByDates {
4519: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4520: my $isCODE=0;
4521: my $isTask = ($symb =~/\.task$/);
4522: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4523: my $studentTable=&Apache::loncommon::start_data_table().
4524: &Apache::loncommon::start_data_table_header_row().
4525: '<th>'.&mt('Date/Time').'</th>'.
4526: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4527: '<th>'.&mt('Submission').'</th>'.
4528: '<th>'.&mt('Status').'</th>'.
4529: &Apache::loncommon::end_data_table_header_row();
4530: my ($version);
4531: my %mark;
4532: my %orders;
4533: $mark{'correct_by_student'} = $checkIcon;
4534: if (!exists($$record{'1:timestamp'})) {
4535: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4536: }
4537:
4538: my $interaction;
4539: my $no_increment = 1;
4540: my %lastrndseed;
4541: for ($version=1;$version<=$$record{'version'};$version++) {
4542: my $timestamp =
4543: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4544: if (exists($$record{$version.':resource.0.version'})) {
4545: $interaction = $$record{$version.':resource.0.version'};
4546: }
4547:
4548: my $where = ($isTask ? "$version:resource.$interaction"
4549: : "$version:resource");
4550: $studentTable.=&Apache::loncommon::start_data_table_row().
4551: '<td>'.$timestamp.'</td>';
4552: if ($isCODE) {
4553: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4554: }
4555: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4556: my @displaySub = ();
4557: foreach my $partid (@{$parts}) {
4558: my ($hidden,$type);
4559: $type = $$record{$version.':resource.'.$partid.'.type'};
4560: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
4561: $hidden = 1;
4562: }
4563: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4564: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4565:
4566: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4567: my $display_part=&get_display_part($partid,$symb);
4568: foreach my $matchKey (@matchKey) {
4569: if (exists($$record{$version.':'.$matchKey}) &&
4570: $$record{$version.':'.$matchKey} ne '') {
4571:
4572: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4573: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4574: $displaySub[0].='<span class="LC_nobreak"';
4575: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4576: .' <span class="LC_internal_info">'
4577: .'('.&mt('Response ID: [_1]',$responseId).')'
4578: .'</span>'
4579: .' <b>';
4580: if ($hidden) {
4581: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4582: } else {
4583: my ($trial,$rndseed,$newvariation);
4584: if ($type eq 'randomizetry') {
4585: $trial = $$record{"$where.$partid.tries"};
4586: $rndseed = $$record{"$where.$partid.rndseed"};
4587: }
4588: if ($$record{"$where.$partid.tries"} eq '') {
4589: $displaySub[0].=&mt('Trial not counted');
4590: } else {
4591: $displaySub[0].=&mt('Trial: [_1]',
4592: $$record{"$where.$partid.tries"});
4593: if ($rndseed || $lastrndseed{$partid}) {
4594: if ($rndseed ne $lastrndseed{$partid}) {
4595: $newvariation = ' ('.&mt('New variation this try').')';
4596: }
4597: }
4598: $lastrndseed{$partid} = $rndseed;
4599: }
4600: my $responseType=($isTask ? 'Task'
4601: : $responseType->{$partid}->{$responseId});
4602: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4603: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
4604: $orders{$partid}->{$responseId}=
4605: &get_order($partid,$responseId,$symb,$uname,$udom,
4606: $no_increment,$type,$trial,$rndseed);
4607: }
4608: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
4609: $displaySub[0].=' '.
4610: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
4611: }
4612: }
4613: }
4614: if (exists($$record{"$where.$partid.checkedin"})) {
4615: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4616: $$record{"$where.$partid.checkedin"},
4617: $$record{"$where.$partid.checkedin.slot"}).
4618: '<br />';
4619: }
4620: if (exists $$record{"$where.$partid.award"}) {
4621: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4622: lc($$record{"$where.$partid.award"}).' '.
4623: $mark{$$record{"$where.$partid.solved"}}.
4624: '<br />';
4625: }
4626: if (exists $$record{"$where.$partid.regrader"}) {
4627: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4628: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4629: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4630: $displaySub[2].=
4631: $$record{"$version:resource.$partid.regrader"}.
4632: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4633: }
4634: }
4635: # needed because old essay regrader has not parts info
4636: if (exists $$record{"$version:resource.regrader"}) {
4637: $displaySub[2].=$$record{"$version:resource.regrader"};
4638: }
4639: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4640: if ($displaySub[2]) {
4641: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4642: }
4643: $studentTable.=' </td>'.
4644: &Apache::loncommon::end_data_table_row();
4645: }
4646: $studentTable.=&Apache::loncommon::end_data_table();
4647: return $studentTable;
4648: }
4649:
4650: sub updateGradeByPage {
4651: my ($request,$symb) = @_;
4652:
4653: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4654: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4655: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4656: my $pageTitle = $env{'form.page'};
4657: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4658: my ($uname,$udom) = split(/:/,$env{'form.student'});
4659: my $usec=$classlist->{$env{'form.student'}}[5];
4660: if (!&canmodify($usec)) {
4661: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4662: return;
4663: }
4664: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4665: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4666: '</h3>'."\n";
4667:
4668: $request->print($result);
4669:
4670:
4671: my $navmap = Apache::lonnavmaps::navmap->new();
4672: unless (ref($navmap)) {
4673: $request->print(&navmap_errormsg());
4674: return;
4675: }
4676: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4677: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4678: if (!$map) {
4679: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4680: return;
4681: }
4682: my $iterator = $navmap->getIterator($map->map_start(),
4683: $map->map_finish());
4684:
4685: my $studentTable=
4686: &Apache::loncommon::start_data_table().
4687: &Apache::loncommon::start_data_table_header_row().
4688: '<th align="center"> '.&mt('Prob.').' </th>'.
4689: '<th> '.&mt('Title').' </th>'.
4690: '<th> '.&mt('Previous Score').' </th>'.
4691: '<th> '.&mt('New Score').' </th>'.
4692: &Apache::loncommon::end_data_table_header_row();
4693:
4694: $iterator->next(); # skip the first BEGIN_MAP
4695: my $curRes = $iterator->next(); # for "current resource"
4696: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4697: while ($depth > 0) {
4698: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4699: if($curRes == $iterator->END_MAP) { $depth--; }
4700:
4701: if (ref($curRes) && $curRes->is_problem()) {
4702: my $parts = $curRes->parts();
4703: my $title = $curRes->compTitle();
4704: my $symbx = $curRes->symb();
4705: $studentTable.=
4706: &Apache::loncommon::start_data_table_row().
4707: '<td align="center" valign="top" >'.$prob.
4708: (scalar(@{$parts}) == 1 ? ''
4709: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
4710: .')').'</td>';
4711: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4712:
4713: my %newrecord=();
4714: my @displayPts=();
4715: my %aggregate = ();
4716: my $aggregateflag = 0;
4717: foreach my $partid (@{$parts}) {
4718: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4719: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4720:
4721: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4722: $env{'form.WGT'.$question.'_'.$partid} : 1;
4723: my $partial = $newpts/$wgt;
4724: my $score;
4725: if ($partial > 0) {
4726: $score = 'correct_by_override';
4727: } elsif ($newpts ne '') { #empty is taken as 0
4728: $score = 'incorrect_by_override';
4729: }
4730: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4731: if ($dropMenu eq 'excused') {
4732: $partial = '';
4733: $score = 'excused';
4734: } elsif ($dropMenu eq 'reset status'
4735: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4736: $newrecord{'resource.'.$partid.'.tries'} = 0;
4737: $newrecord{'resource.'.$partid.'.solved'} = '';
4738: $newrecord{'resource.'.$partid.'.award'} = '';
4739: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4740: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4741: $changeflag++;
4742: $newpts = '';
4743:
4744: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4745: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4746: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4747: if ($aggtries > 0) {
4748: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4749: $aggregateflag = 1;
4750: }
4751: }
4752: my $display_part=&get_display_part($partid,$curRes->symb());
4753: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4754: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4755: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4756: ' <br />';
4757: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4758: (($score eq 'excused') ? 'excused' : $newpts).
4759: ' <br />';
4760: $question++;
4761: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4762:
4763: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4764: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4765: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4766: if (scalar(keys(%newrecord)) > 0);
4767:
4768: $changeflag++;
4769: }
4770: if (scalar(keys(%newrecord)) > 0) {
4771: my %record =
4772: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4773: $udom,$uname);
4774:
4775: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4776: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4777: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4778: $newrecord{'resource.CODE'} = '';
4779: }
4780: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4781: $udom,$uname);
4782: %record = &Apache::lonnet::restore($symbx,
4783: $env{'request.course.id'},
4784: $udom,$uname);
4785: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4786: $cdom,$cnum,$udom,$uname);
4787: }
4788:
4789: if ($aggregateflag) {
4790: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4791: $env{'course.'.$env{'request.course.id'}.'.domain'},
4792: $env{'course.'.$env{'request.course.id'}.'.num'});
4793: }
4794:
4795: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4796: '<td valign="top">'.$displayPts[1].'</td>'.
4797: &Apache::loncommon::end_data_table_row();
4798:
4799: $prob++;
4800: }
4801: $curRes = $iterator->next();
4802: }
4803:
4804: $studentTable.=&Apache::loncommon::end_data_table();
4805: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
4806: &mt('The scores were changed for [quant,_1,problem].',
4807: $changeflag));
4808: $request->print($grademsg.$studentTable);
4809:
4810: return '';
4811: }
4812:
4813: #-------- end of section for handling grading by page/sequence ---------
4814: #
4815: #-------------------------------------------------------------------
4816:
4817: #-------------------- Bubblesheet (Scantron) Grading -------------------
4818: #
4819: #------ start of section for handling grading by page/sequence ---------
4820:
4821: =pod
4822:
4823: =head1 Bubble sheet grading routines
4824:
4825: For this documentation:
4826:
4827: 'scanline' refers to the full line of characters
4828: from the file that we are parsing that represents one entire sheet
4829:
4830: 'bubble line' refers to the data
4831: representing the line of bubbles that are on the physical bubble sheet
4832:
4833:
4834: The overall process is that a scanned in bubble sheet data is uploaded
4835: into a course. When a user wants to grade, they select a
4836: sequence/folder of resources, a file of bubble sheet info, and pick
4837: one of the predefined configurations for what each scanline looks
4838: like.
4839:
4840: Next each scanline is checked for any errors of either 'missing
4841: bubbles' (it's an error because it may have been mis-scanned
4842: because too light bubbling), 'double bubble' (each bubble line should
4843: have no more that one letter picked), invalid or duplicated CODE,
4844: invalid student/employee ID
4845:
4846: If the CODE option is used that determines the randomization of the
4847: homework problems, either way the student/employee ID is looked up into a
4848: username:domain.
4849:
4850: During the validation phase the instructor can choose to skip scanlines.
4851:
4852: After the validation phase, there are now 3 bubble sheet files
4853:
4854: scantron_original_filename (unmodified original file)
4855: scantron_corrected_filename (file where the corrected information has replaced the original information)
4856: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4857:
4858: Also there is a separate hash nohist_scantrondata that contains extra
4859: correction information that isn't representable in the bubble sheet
4860: file (see &scantron_getfile() for more information)
4861:
4862: After all scanlines are either valid, marked as valid or skipped, then
4863: foreach line foreach problem in the picked sequence, an ssi request is
4864: made that simulates a user submitting their selected letter(s) against
4865: the homework problem.
4866:
4867: =over 4
4868:
4869:
4870:
4871: =item defaultFormData
4872:
4873: Returns html hidden inputs used to hold context/default values.
4874:
4875: Arguments:
4876: $symb - $symb of the current resource
4877:
4878: =cut
4879:
4880: sub defaultFormData {
4881: my ($symb)=@_;
4882: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
4883: }
4884:
4885:
4886: =pod
4887:
4888: =item getSequenceDropDown
4889:
4890: Return html dropdown of possible sequences to grade
4891:
4892: Arguments:
4893: $symb - $symb of the current resource
4894: $map_error - ref to scalar which will container error if
4895: $navmap object is unavailable in &getSymbMap().
4896:
4897: =cut
4898:
4899: sub getSequenceDropDown {
4900: my ($symb,$map_error)=@_;
4901: my $result='<select name="selectpage">'."\n";
4902: my ($titles,$symbx) = &getSymbMap($map_error);
4903: if (ref($map_error)) {
4904: return if ($$map_error);
4905: }
4906: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4907: my $ctr=0;
4908: foreach (@$titles) {
4909: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4910: $result.='<option value="'.$$symbx{$_}.'" '.
4911: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4912: '>'.$showtitle.'</option>'."\n";
4913: $ctr++;
4914: }
4915: $result.= '</select>';
4916: return $result;
4917: }
4918:
4919: my %bubble_lines_per_response; # no. bubble lines for each response.
4920: # key is zero-based index - 0, 1, 2 ...
4921:
4922: my %first_bubble_line; # First bubble line no. for each bubble.
4923:
4924: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
4925: # matchresponse or rankresponse, where
4926: # an individual response can have multiple
4927: # lines
4928:
4929: my %responsetype_per_response; # responsetype for each response
4930:
4931: # Save and restore the bubble lines array to the form env.
4932:
4933:
4934: sub save_bubble_lines {
4935: foreach my $line (keys(%bubble_lines_per_response)) {
4936: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
4937: $env{"form.scantron.first_bubble_line.$line"} =
4938: $first_bubble_line{$line};
4939: $env{"form.scantron.sub_bubblelines.$line"} =
4940: $subdivided_bubble_lines{$line};
4941: $env{"form.scantron.responsetype.$line"} =
4942: $responsetype_per_response{$line};
4943: }
4944: }
4945:
4946:
4947: sub restore_bubble_lines {
4948: my $line = 0;
4949: %bubble_lines_per_response = ();
4950: while ($env{"form.scantron.bubblelines.$line"}) {
4951: my $value = $env{"form.scantron.bubblelines.$line"};
4952: $bubble_lines_per_response{$line} = $value;
4953: $first_bubble_line{$line} =
4954: $env{"form.scantron.first_bubble_line.$line"};
4955: $subdivided_bubble_lines{$line} =
4956: $env{"form.scantron.sub_bubblelines.$line"};
4957: $responsetype_per_response{$line} =
4958: $env{"form.scantron.responsetype.$line"};
4959: $line++;
4960: }
4961: }
4962:
4963: # Given the parsed scanline, get the response for
4964: # 'answer' number n:
4965:
4966: sub get_response_bubbles {
4967: my ($parsed_line, $response) = @_;
4968:
4969: my $bubble_line = $first_bubble_line{$response-1} +1;
4970: my $bubble_lines= $bubble_lines_per_response{$response-1};
4971:
4972: my $selected = "";
4973:
4974: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
4975: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
4976: $bubble_line++;
4977: }
4978: return $selected;
4979: }
4980:
4981: =pod
4982:
4983: =item scantron_filenames
4984:
4985: Returns a list of the scantron files in the current course
4986:
4987: =cut
4988:
4989: sub scantron_filenames {
4990: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4991: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4992: my $getpropath = 1;
4993: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4994: $getpropath);
4995: my @possiblenames;
4996: foreach my $filename (sort(@files)) {
4997: ($filename)=split(/&/,$filename);
4998: if ($filename!~/^scantron_orig_/) { next ; }
4999: $filename=~s/^scantron_orig_//;
5000: push(@possiblenames,$filename);
5001: }
5002: return @possiblenames;
5003: }
5004:
5005: =pod
5006:
5007: =item scantron_uploads
5008:
5009: Returns html drop-down list of scantron files in current course.
5010:
5011: Arguments:
5012: $file2grade - filename to set as selected in the dropdown
5013:
5014: =cut
5015:
5016: sub scantron_uploads {
5017: my ($file2grade) = @_;
5018: my $result= '<select name="scantron_selectfile">';
5019: $result.="<option></option>";
5020: foreach my $filename (sort(&scantron_filenames())) {
5021: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5022: }
5023: $result.="</select>";
5024: return $result;
5025: }
5026:
5027: =pod
5028:
5029: =item scantron_scantab
5030:
5031: Returns html drop down of the scantron formats in the scantronformat.tab
5032: file.
5033:
5034: =cut
5035:
5036: sub scantron_scantab {
5037: my $result='<select name="scantron_format">'."\n";
5038: $result.='<option></option>'."\n";
5039: my @lines = &get_scantronformat_file();
5040: if (@lines > 0) {
5041: foreach my $line (@lines) {
5042: next if (($line =~ /^\#/) || ($line eq ''));
5043: my ($name,$descrip)=split(/:/,$line);
5044: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5045: }
5046: }
5047: $result.='</select>'."\n";
5048: return $result;
5049: }
5050:
5051: =pod
5052:
5053: =item get_scantronformat_file
5054:
5055: Returns an array containing lines from the scantron format file for
5056: the domain of the course.
5057:
5058: If a url for a custom.tab file is listed in domain's configuration.db,
5059: lines are from this file.
5060:
5061: Otherwise, if a default.tab has been published in RES space by the
5062: domainconfig user, lines are from this file.
5063:
5064: Otherwise, fall back to getting lines from the legacy file on the
5065: local server: /home/httpd/lonTabs/default_scantronformat.tab
5066:
5067: =cut
5068:
5069: sub get_scantronformat_file {
5070: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5071: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5072: my $gottab = 0;
5073: my @lines;
5074: if (ref($domconfig{'scantron'}) eq 'HASH') {
5075: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5076: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5077: if ($formatfile ne '-1') {
5078: @lines = split("\n",$formatfile,-1);
5079: $gottab = 1;
5080: }
5081: }
5082: }
5083: if (!$gottab) {
5084: my $confname = $cdom.'-domainconfig';
5085: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5086: my $formatfile = &Apache::lonnet::getfile($default);
5087: if ($formatfile ne '-1') {
5088: @lines = split("\n",$formatfile,-1);
5089: $gottab = 1;
5090: }
5091: }
5092: if (!$gottab) {
5093: my @domains = &Apache::lonnet::current_machine_domains();
5094: if (grep(/^\Q$cdom\E$/,@domains)) {
5095: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5096: @lines = <$fh>;
5097: close($fh);
5098: } else {
5099: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5100: @lines = <$fh>;
5101: close($fh);
5102: }
5103: }
5104: return @lines;
5105: }
5106:
5107: =pod
5108:
5109: =item scantron_CODElist
5110:
5111: Returns html drop down of the saved CODE lists from current course,
5112: generated from earlier printings.
5113:
5114: =cut
5115:
5116: sub scantron_CODElist {
5117: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5118: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5119: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5120: my $namechoice='<option></option>';
5121: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5122: if ($name =~ /^error: 2 /) { next; }
5123: if ($name =~ /^type\0/) { next; }
5124: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5125: }
5126: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5127: return $namechoice;
5128: }
5129:
5130: =pod
5131:
5132: =item scantron_CODEunique
5133:
5134: Returns the html for "Each CODE to be used once" radio.
5135:
5136: =cut
5137:
5138: sub scantron_CODEunique {
5139: my $result='<span class="LC_nobreak">
5140: <label><input type="radio" name="scantron_CODEunique"
5141: value="yes" checked="checked" />'.&mt('Yes').' </label>
5142: </span>
5143: <span class="LC_nobreak">
5144: <label><input type="radio" name="scantron_CODEunique"
5145: value="no" />'.&mt('No').' </label>
5146: </span>';
5147: return $result;
5148: }
5149:
5150: =pod
5151:
5152: =item scantron_selectphase
5153:
5154: Generates the initial screen to start the bubble sheet process.
5155: Allows for - starting a grading run.
5156: - downloading existing scan data (original, corrected
5157: or skipped info)
5158:
5159: - uploading new scan data
5160:
5161: Arguments:
5162: $r - The Apache request object
5163: $file2grade - name of the file that contain the scanned data to score
5164:
5165: =cut
5166:
5167: sub scantron_selectphase {
5168: my ($r,$file2grade,$symb) = @_;
5169: if (!$symb) {return '';}
5170: my $map_error;
5171: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5172: if ($map_error) {
5173: $r->print('<br />'.&navmap_errormsg().'<br />');
5174: return;
5175: }
5176: my $default_form_data=&defaultFormData($symb);
5177: my $file_selector=&scantron_uploads($file2grade);
5178: my $format_selector=&scantron_scantab();
5179: my $CODE_selector=&scantron_CODElist();
5180: my $CODE_unique=&scantron_CODEunique();
5181: my $result;
5182:
5183: $ssi_error = 0;
5184:
5185: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5186: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5187:
5188: # Chunk of form to prompt for a scantron file upload.
5189:
5190: $r->print('
5191: <br />
5192: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5193: '.&Apache::loncommon::start_data_table_header_row().'
5194: <th>
5195: '.&mt('Specify a bubblesheet data file to upload.').'
5196: </th>
5197: '.&Apache::loncommon::end_data_table_header_row().'
5198: '.&Apache::loncommon::start_data_table_row().'
5199: <td>
5200: ');
5201: my $default_form_data=&defaultFormData($symb);
5202: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5203: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5204: $r->print(&Apache::lonhtmlcommon::scripttag('
5205: function checkUpload(formname) {
5206: if (formname.upfile.value == "") {
5207: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5208: return false;
5209: }
5210: formname.submit();
5211: }'));
5212: $r->print('
5213: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5214: '.$default_form_data.'
5215: <input name="courseid" type="hidden" value="'.$cnum.'" />
5216: <input name="domainid" type="hidden" value="'.$cdom.'" />
5217: <input name="command" value="scantronupload_save" type="hidden" />
5218: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5219: <br />
5220: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5221: </form>
5222: ');
5223:
5224: $r->print('
5225: </td>
5226: '.&Apache::loncommon::end_data_table_row().'
5227: '.&Apache::loncommon::end_data_table().'
5228: ');
5229: }
5230:
5231: # Chunk of form to prompt for a file to grade and how:
5232:
5233: $result.= '
5234: <br />
5235: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5236: <input type="hidden" name="command" value="scantron_warning" />
5237: '.$default_form_data.'
5238: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5239: '.&Apache::loncommon::start_data_table_header_row().'
5240: <th colspan="2">
5241: '.&mt('Specify file and which Folder/Sequence to grade').'
5242: </th>
5243: '.&Apache::loncommon::end_data_table_header_row().'
5244: '.&Apache::loncommon::start_data_table_row().'
5245: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5246: '.&Apache::loncommon::end_data_table_row().'
5247: '.&Apache::loncommon::start_data_table_row().'
5248: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5249: '.&Apache::loncommon::end_data_table_row().'
5250: '.&Apache::loncommon::start_data_table_row().'
5251: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5252: '.&Apache::loncommon::end_data_table_row().'
5253: '.&Apache::loncommon::start_data_table_row().'
5254: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5255: '.&Apache::loncommon::end_data_table_row().'
5256: '.&Apache::loncommon::start_data_table_row().'
5257: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5258: '.&Apache::loncommon::end_data_table_row().'
5259: '.&Apache::loncommon::start_data_table_row().'
5260: <td> '.&mt('Options:').' </td>
5261: <td>
5262: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5263: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5264: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5265: </td>
5266: '.&Apache::loncommon::end_data_table_row().'
5267: '.&Apache::loncommon::start_data_table_row().'
5268: <td colspan="2">
5269: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5270: </td>
5271: '.&Apache::loncommon::end_data_table_row().'
5272: '.&Apache::loncommon::end_data_table().'
5273: </form>
5274: ';
5275:
5276: $r->print($result);
5277:
5278:
5279:
5280: # Chunk of the form that prompts to view a scoring office file,
5281: # corrected file, skipped records in a file.
5282:
5283: $r->print('
5284: <br />
5285: <form action="/adm/grades" name="scantron_download">
5286: '.$default_form_data.'
5287: <input type="hidden" name="command" value="scantron_download" />
5288: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5289: '.&Apache::loncommon::start_data_table_header_row().'
5290: <th>
5291: '.&mt('Download a scoring office file').'
5292: </th>
5293: '.&Apache::loncommon::end_data_table_header_row().'
5294: '.&Apache::loncommon::start_data_table_row().'
5295: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5296: <br />
5297: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5298: '.&Apache::loncommon::end_data_table_row().'
5299: '.&Apache::loncommon::end_data_table().'
5300: </form>
5301: <br />
5302: ');
5303:
5304: &Apache::lonpickcode::code_list($r,2);
5305:
5306: $r->print('<br /><form method="post" name="checkscantron">'.
5307: $default_form_data."\n".
5308: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5309: &Apache::loncommon::start_data_table_header_row()."\n".
5310: '<th colspan="2">
5311: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5312: '</th>'."\n".
5313: &Apache::loncommon::end_data_table_header_row()."\n".
5314: &Apache::loncommon::start_data_table_row()."\n".
5315: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5316: '<td> '.$sequence_selector.' </td>'.
5317: &Apache::loncommon::end_data_table_row()."\n".
5318: &Apache::loncommon::start_data_table_row()."\n".
5319: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5320: '<td> '.$file_selector.' </td>'."\n".
5321: &Apache::loncommon::end_data_table_row()."\n".
5322: &Apache::loncommon::start_data_table_row()."\n".
5323: '<td> '.&mt('Format of data file:').' </td>'."\n".
5324: '<td> '.$format_selector.' </td>'."\n".
5325: &Apache::loncommon::end_data_table_row()."\n".
5326: &Apache::loncommon::start_data_table_row()."\n".
5327: '<td> '.&mt('Options').' </td>'."\n".
5328: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5329: &Apache::loncommon::end_data_table_row()."\n".
5330: &Apache::loncommon::start_data_table_row()."\n".
5331: '<td colspan="2">'."\n".
5332: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5333: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5334: '</td>'."\n".
5335: &Apache::loncommon::end_data_table_row()."\n".
5336: &Apache::loncommon::end_data_table()."\n".
5337: '</form><br />');
5338: return;
5339: }
5340:
5341: =pod
5342:
5343: =item get_scantron_config
5344:
5345: Parse and return the scantron configuration line selected as a
5346: hash of configuration file fields.
5347:
5348: Arguments:
5349: which - the name of the configuration to parse from the file.
5350:
5351:
5352: Returns:
5353: If the named configuration is not in the file, an empty
5354: hash is returned.
5355: a hash with the fields
5356: name - internal name for the this configuration setup
5357: description - text to display to operator that describes this config
5358: CODElocation - if 0 or the string 'none'
5359: - no CODE exists for this config
5360: if -1 || the string 'letter'
5361: - a CODE exists for this config and is
5362: a string of letters
5363: Unsupported value (but planned for future support)
5364: if a positive integer
5365: - The CODE exists as the first n items from
5366: the question section of the form
5367: if the string 'number'
5368: - The CODE exists for this config and is
5369: a string of numbers
5370: CODEstart - (only matter if a CODE exists) column in the line where
5371: the CODE starts
5372: CODElength - length of the CODE
5373: IDstart - column where the student/employee ID starts
5374: IDlength - length of the student/employee ID info
5375: Qstart - column where the information from the bubbled
5376: 'questions' start
5377: Qlength - number of columns comprising a single bubble line from
5378: the sheet. (usually either 1 or 10)
5379: Qon - either a single character representing the character used
5380: to signal a bubble was chosen in the positional setup, or
5381: the string 'letter' if the letter of the chosen bubble is
5382: in the final, or 'number' if a number representing the
5383: chosen bubble is in the file (1->A 0->J)
5384: Qoff - the character used to represent that a bubble was
5385: left blank
5386: PaperID - if the scanning process generates a unique number for each
5387: sheet scanned the column that this ID number starts in
5388: PaperIDlength - number of columns that comprise the unique ID number
5389: for the sheet of paper
5390: FirstName - column that the first name starts in
5391: FirstNameLength - number of columns that the first name spans
5392:
5393: LastName - column that the last name starts in
5394: LastNameLength - number of columns that the last name spans
5395: BubblesPerRow - number of bubbles available in each row used to
5396: bubble an answer. (If not specified, 10 assumed).
5397: =cut
5398:
5399: sub get_scantron_config {
5400: my ($which) = @_;
5401: my @lines = &get_scantronformat_file();
5402: my %config;
5403: #FIXME probably should move to XML it has already gotten a bit much now
5404: foreach my $line (@lines) {
5405: my ($name,$descrip)=split(/:/,$line);
5406: if ($name ne $which ) { next; }
5407: chomp($line);
5408: my @config=split(/:/,$line);
5409: $config{'name'}=$config[0];
5410: $config{'description'}=$config[1];
5411: $config{'CODElocation'}=$config[2];
5412: $config{'CODEstart'}=$config[3];
5413: $config{'CODElength'}=$config[4];
5414: $config{'IDstart'}=$config[5];
5415: $config{'IDlength'}=$config[6];
5416: $config{'Qstart'}=$config[7];
5417: $config{'Qlength'}=$config[8];
5418: $config{'Qoff'}=$config[9];
5419: $config{'Qon'}=$config[10];
5420: $config{'PaperID'}=$config[11];
5421: $config{'PaperIDlength'}=$config[12];
5422: $config{'FirstName'}=$config[13];
5423: $config{'FirstNamelength'}=$config[14];
5424: $config{'LastName'}=$config[15];
5425: $config{'LastNamelength'}=$config[16];
5426: $config{'BubblesPerRow'}=$config[17];
5427: last;
5428: }
5429: return %config;
5430: }
5431:
5432: =pod
5433:
5434: =item username_to_idmap
5435:
5436: creates a hash keyed by student/employee ID with values of the corresponding
5437: student username:domain.
5438:
5439: Arguments:
5440:
5441: $classlist - reference to the class list hash. This is a hash
5442: keyed by student name:domain whose elements are references
5443: to arrays containing various chunks of information
5444: about the student. (See loncoursedata for more info).
5445:
5446: Returns
5447: %idmap - the constructed hash
5448:
5449: =cut
5450:
5451: sub username_to_idmap {
5452: my ($classlist)= @_;
5453: my %idmap;
5454: foreach my $student (keys(%$classlist)) {
5455: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5456: $student;
5457: }
5458: return %idmap;
5459: }
5460:
5461: =pod
5462:
5463: =item scantron_fixup_scanline
5464:
5465: Process a requested correction to a scanline.
5466:
5467: Arguments:
5468: $scantron_config - hash from &get_scantron_config()
5469: $scan_data - hash of correction information
5470: (see &scantron_getfile())
5471: $line - existing scanline
5472: $whichline - line number of the passed in scanline
5473: $field - type of change to process
5474: (either
5475: 'ID' -> correct the student/employee ID
5476: 'CODE' -> correct the CODE
5477: 'answer' -> fixup the submitted answers)
5478:
5479: $args - hash of additional info,
5480: - 'ID'
5481: 'newid' -> studentID to use in replacement
5482: of existing one
5483: - 'CODE'
5484: 'CODE_ignore_dup' - set to true if duplicates
5485: should be ignored.
5486: 'CODE' - is new code or 'use_unfound'
5487: if the existing unfound code should
5488: be used as is
5489: - 'answer'
5490: 'response' - new answer or 'none' if blank
5491: 'question' - the bubble line to change
5492: 'questionnum' - the question identifier,
5493: may include subquestion.
5494:
5495: Returns:
5496: $line - the modified scanline
5497:
5498: Side effects:
5499: $scan_data - may be updated
5500:
5501: =cut
5502:
5503:
5504: sub scantron_fixup_scanline {
5505: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5506: if ($field eq 'ID') {
5507: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5508: return ($line,1,'New value too large');
5509: }
5510: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5511: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5512: $args->{'newid'});
5513: }
5514: substr($line,$$scantron_config{'IDstart'}-1,
5515: $$scantron_config{'IDlength'})=$args->{'newid'};
5516: if ($args->{'newid'}=~/^\s*$/) {
5517: &scan_data($scan_data,"$whichline.user",
5518: $args->{'username'}.':'.$args->{'domain'});
5519: }
5520: } elsif ($field eq 'CODE') {
5521: if ($args->{'CODE_ignore_dup'}) {
5522: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5523: }
5524: &scan_data($scan_data,"$whichline.useCODE",'1');
5525: if ($args->{'CODE'} ne 'use_unfound') {
5526: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5527: return ($line,1,'New CODE value too large');
5528: }
5529: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5530: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5531: }
5532: substr($line,$$scantron_config{'CODEstart'}-1,
5533: $$scantron_config{'CODElength'})=$args->{'CODE'};
5534: }
5535: } elsif ($field eq 'answer') {
5536: my $length=$scantron_config->{'Qlength'};
5537: my $off=$scantron_config->{'Qoff'};
5538: my $on=$scantron_config->{'Qon'};
5539: my $answer=${off}x$length;
5540: if ($args->{'response'} eq 'none') {
5541: &scan_data($scan_data,
5542: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5543: } else {
5544: if ($on eq 'letter') {
5545: my @alphabet=('A'..'Z');
5546: $answer=$alphabet[$args->{'response'}];
5547: } elsif ($on eq 'number') {
5548: $answer=$args->{'response'}+1;
5549: if ($answer == 10) { $answer = '0'; }
5550: } else {
5551: substr($answer,$args->{'response'},1)=$on;
5552: }
5553: &scan_data($scan_data,
5554: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5555: }
5556: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5557: substr($line,$where-1,$length)=$answer;
5558: }
5559: return $line;
5560: }
5561:
5562: =pod
5563:
5564: =item scan_data
5565:
5566: Edit or look up an item in the scan_data hash.
5567:
5568: Arguments:
5569: $scan_data - The hash (see scantron_getfile)
5570: $key - shorthand of the key to edit (actual key is
5571: scantronfilename_key).
5572: $data - New value of the hash entry.
5573: $delete - If true, the entry is removed from the hash.
5574:
5575: Returns:
5576: The new value of the hash table field (undefined if deleted).
5577:
5578: =cut
5579:
5580:
5581: sub scan_data {
5582: my ($scan_data,$key,$value,$delete)=@_;
5583: my $filename=$env{'form.scantron_selectfile'};
5584: if (defined($value)) {
5585: $scan_data->{$filename.'_'.$key} = $value;
5586: }
5587: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5588: return $scan_data->{$filename.'_'.$key};
5589: }
5590:
5591: # ----- These first few routines are general use routines.----
5592:
5593: # Return the number of occurences of a pattern in a string.
5594:
5595: sub occurence_count {
5596: my ($string, $pattern) = @_;
5597:
5598: my @matches = ($string =~ /$pattern/g);
5599:
5600: return scalar(@matches);
5601: }
5602:
5603:
5604: # Take a string known to have digits and convert all the
5605: # digits into letters in the range J,A..I.
5606:
5607: sub digits_to_letters {
5608: my ($input) = @_;
5609:
5610: my @alphabet = ('J', 'A'..'I');
5611:
5612: my @input = split(//, $input);
5613: my $output ='';
5614: for (my $i = 0; $i < scalar(@input); $i++) {
5615: if ($input[$i] =~ /\d/) {
5616: $output .= $alphabet[$input[$i]];
5617: } else {
5618: $output .= $input[$i];
5619: }
5620: }
5621: return $output;
5622: }
5623:
5624: =pod
5625:
5626: =item scantron_parse_scanline
5627:
5628: Decodes a scanline from the selected scantron file
5629:
5630: Arguments:
5631: line - The text of the scantron file line to process
5632: whichline - Line number
5633: scantron_config - Hash describing the format of the scantron lines.
5634: scan_data - Hash of extra information about the scanline
5635: (see scantron_getfile for more information)
5636: just_header - True if should not process question answers but only
5637: the stuff to the left of the answers.
5638: Returns:
5639: Hash containing the result of parsing the scanline
5640:
5641: Keys are all proceeded by the string 'scantron.'
5642:
5643: CODE - the CODE in use for this scanline
5644: useCODE - 1 if the CODE is invalid but it usage has been forced
5645: by the operator
5646: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5647: CODEs were selected, but the usage has been
5648: forced by the operator
5649: ID - student/employee ID
5650: PaperID - if used, the ID number printed on the sheet when the
5651: paper was scanned
5652: FirstName - first name from the sheet
5653: LastName - last name from the sheet
5654:
5655: if just_header was not true these key may also exist
5656:
5657: missingerror - a list of bubble ranges that are considered to be answers
5658: to a single question that don't have any bubbles filled in.
5659: Of the form questionnumber:firstbubblenumber:count.
5660: doubleerror - a list of bubble ranges that are considered to be answers
5661: to a single question that have more than one bubble filled in.
5662: Of the form questionnumber::firstbubblenumber:count
5663:
5664: In the above, count is the number of bubble responses in the
5665: input line needed to represent the possible answers to the question.
5666: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5667: per line would have count = 2.
5668:
5669: maxquest - the number of the last bubble line that was parsed
5670:
5671: (<number> starts at 1)
5672: <number>.answer - zero or more letters representing the selected
5673: letters from the scanline for the bubble line
5674: <number>.
5675: if blank there was either no bubble or there where
5676: multiple bubbles, (consult the keys missingerror and
5677: doubleerror if this is an error condition)
5678:
5679: =cut
5680:
5681: sub scantron_parse_scanline {
5682: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5683:
5684: my %record;
5685: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
5686: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
5687: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5688: if (!($$scantron_config{'CODElocation'} eq 0 ||
5689: $$scantron_config{'CODElocation'} eq 'none')) {
5690: if ($$scantron_config{'CODElocation'} < 0 ||
5691: $$scantron_config{'CODElocation'} eq 'letter' ||
5692: $$scantron_config{'CODElocation'} eq 'number') {
5693: $record{'scantron.CODE'}=substr($data,
5694: $$scantron_config{'CODEstart'}-1,
5695: $$scantron_config{'CODElength'});
5696: if (&scan_data($scan_data,"$whichline.useCODE")) {
5697: $record{'scantron.useCODE'}=1;
5698: }
5699: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5700: $record{'scantron.CODE_ignore_dup'}=1;
5701: }
5702: } else {
5703: #FIXME interpret first N questions
5704: }
5705: }
5706: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5707: $$scantron_config{'IDlength'});
5708: $record{'scantron.PaperID'}=
5709: substr($data,$$scantron_config{'PaperID'}-1,
5710: $$scantron_config{'PaperIDlength'});
5711: $record{'scantron.FirstName'}=
5712: substr($data,$$scantron_config{'FirstName'}-1,
5713: $$scantron_config{'FirstNamelength'});
5714: $record{'scantron.LastName'}=
5715: substr($data,$$scantron_config{'LastName'}-1,
5716: $$scantron_config{'LastNamelength'});
5717: if ($just_header) { return \%record; }
5718:
5719: my @alphabet=('A'..'Z');
5720: my $questnum=0;
5721: my $ansnum =1; # Multiple 'answer lines'/question.
5722:
5723: chomp($questions); # Get rid of any trailing \n.
5724: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5725: while (length($questions)) {
5726: my $answers_needed = $bubble_lines_per_response{$questnum};
5727: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
5728: || 1;
5729: $questnum++;
5730: my $quest_id = $questnum;
5731: my $currentquest = substr($questions,0,$answer_length);
5732: $questions = substr($questions,$answer_length);
5733: if (length($currentquest) < $answer_length) { next; }
5734:
5735: if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
5736: my $subquestnum = 1;
5737: my $subquestions = $currentquest;
5738: my @subanswers_needed =
5739: split(/,/,$subdivided_bubble_lines{$questnum-1});
5740: foreach my $subans (@subanswers_needed) {
5741: my $subans_length =
5742: ($$scantron_config{'Qlength'} * $subans) || 1;
5743: my $currsubquest = substr($subquestions,0,$subans_length);
5744: $subquestions = substr($subquestions,$subans_length);
5745: $quest_id = "$questnum.$subquestnum";
5746: if (($$scantron_config{'Qon'} eq 'letter') ||
5747: ($$scantron_config{'Qon'} eq 'number')) {
5748: $ansnum = &scantron_validator_lettnum($ansnum,
5749: $questnum,$quest_id,$subans,$currsubquest,$whichline,
5750: \@alphabet,\%record,$scantron_config,$scan_data);
5751: } else {
5752: $ansnum = &scantron_validator_positional($ansnum,
5753: $questnum,$quest_id,$subans,$currsubquest,$whichline, \@alphabet,\%record,$scantron_config,$scan_data);
5754: }
5755: $subquestnum ++;
5756: }
5757: } else {
5758: if (($$scantron_config{'Qon'} eq 'letter') ||
5759: ($$scantron_config{'Qon'} eq 'number')) {
5760: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
5761: $quest_id,$answers_needed,$currentquest,$whichline,
5762: \@alphabet,\%record,$scantron_config,$scan_data);
5763: } else {
5764: $ansnum = &scantron_validator_positional($ansnum,$questnum,
5765: $quest_id,$answers_needed,$currentquest,$whichline,
5766: \@alphabet,\%record,$scantron_config,$scan_data);
5767: }
5768: }
5769: }
5770: $record{'scantron.maxquest'}=$questnum;
5771: return \%record;
5772: }
5773:
5774: sub scantron_validator_lettnum {
5775: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
5776: $alphabet,$record,$scantron_config,$scan_data) = @_;
5777:
5778: # Qon 'letter' implies for each slot in currquest we have:
5779: # ? or * for doubles, a letter in A-Z for a bubble, and
5780: # about anything else (esp. a value of Qoff) for missing
5781: # bubbles.
5782: #
5783: # Qon 'number' implies each slot gives a digit that indexes the
5784: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
5785: # and * or ? for double bubbles on a single line.
5786: #
5787:
5788: my $matchon;
5789: if ($$scantron_config{'Qon'} eq 'letter') {
5790: $matchon = '[A-Z]';
5791: } elsif ($$scantron_config{'Qon'} eq 'number') {
5792: $matchon = '\d';
5793: }
5794: my $occurrences = 0;
5795: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5796: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5797: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5798: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5799: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5800: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5801: my @singlelines = split('',$currquest);
5802: foreach my $entry (@singlelines) {
5803: $occurrences = &occurence_count($entry,$matchon);
5804: if ($occurrences > 1) {
5805: last;
5806: }
5807: }
5808: } else {
5809: $occurrences = &occurence_count($currquest,$matchon);
5810: }
5811: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
5812: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5813: for (my $ans=0; $ans<$answers_needed; $ans++) {
5814: my $bubble = substr($currquest,$ans,1);
5815: if ($bubble =~ /$matchon/ ) {
5816: if ($$scantron_config{'Qon'} eq 'number') {
5817: if ($bubble == 0) {
5818: $bubble = 10;
5819: }
5820: $record->{"scantron.$ansnum.answer"} =
5821: $alphabet->[$bubble-1];
5822: } else {
5823: $record->{"scantron.$ansnum.answer"} = $bubble;
5824: }
5825: } else {
5826: $record->{"scantron.$ansnum.answer"}='';
5827: }
5828: $ansnum++;
5829: }
5830: } elsif (!defined($currquest)
5831: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
5832: || (&occurence_count($currquest,$matchon) == 0)) {
5833: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5834: $record->{"scantron.$ansnum.answer"}='';
5835: $ansnum++;
5836: }
5837: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5838: push(@{$record->{'scantron.missingerror'}},$quest_id);
5839: }
5840: } else {
5841: if ($$scantron_config{'Qon'} eq 'number') {
5842: $currquest = &digits_to_letters($currquest);
5843: }
5844: for (my $ans=0; $ans<$answers_needed; $ans++) {
5845: my $bubble = substr($currquest,$ans,1);
5846: $record->{"scantron.$ansnum.answer"} = $bubble;
5847: $ansnum++;
5848: }
5849: }
5850: return $ansnum;
5851: }
5852:
5853: sub scantron_validator_positional {
5854: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
5855: $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
5856:
5857: # Otherwise there's a positional notation;
5858: # each bubble line requires Qlength items, and there are filled in
5859: # bubbles for each case where there 'Qon' characters.
5860: #
5861:
5862: my @array=split($$scantron_config{'Qon'},$currquest,-1);
5863:
5864: # If the split only gives us one element.. the full length of the
5865: # answer string, no bubbles are filled in:
5866:
5867: if ($answers_needed eq '') {
5868: return;
5869: }
5870:
5871: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5872: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5873: $record->{"scantron.$ansnum.answer"}='';
5874: $ansnum++;
5875: }
5876: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5877: push(@{$record->{"scantron.missingerror"}},$quest_id);
5878: }
5879: } elsif (scalar(@array) == 2) {
5880: my $location = length($array[0]);
5881: my $line_num = int($location / $$scantron_config{'Qlength'});
5882: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
5883: for (my $ans=0; $ans<$answers_needed; $ans++) {
5884: if ($ans eq $line_num) {
5885: $record->{"scantron.$ansnum.answer"} = $bubble;
5886: } else {
5887: $record->{"scantron.$ansnum.answer"} = ' ';
5888: }
5889: $ansnum++;
5890: }
5891: } else {
5892: # If there's more than one instance of a bubble character
5893: # That's a double bubble; with positional notation we can
5894: # record all the bubbles filled in as well as the
5895: # fact this response consists of multiple bubbles.
5896: #
5897: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5898: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5899: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5900: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5901: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5902: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5903: my $doubleerror = 0;
5904: while (($currquest >= $$scantron_config{'Qlength'}) &&
5905: (!$doubleerror)) {
5906: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
5907: $currquest = substr($currquest,$$scantron_config{'Qlength'});
5908: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
5909: if (length(@currarray) > 2) {
5910: $doubleerror = 1;
5911: }
5912: }
5913: if ($doubleerror) {
5914: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5915: }
5916: } else {
5917: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5918: }
5919: my $item = $ansnum;
5920: for (my $ans=0; $ans<$answers_needed; $ans++) {
5921: $record->{"scantron.$item.answer"} = '';
5922: $item ++;
5923: }
5924:
5925: my @ans=@array;
5926: my $i=0;
5927: my $increment = 0;
5928: while ($#ans) {
5929: $i+=length($ans[0]) + $increment;
5930: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
5931: my $bubble = $i%$$scantron_config{'Qlength'};
5932: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
5933: shift(@ans);
5934: $increment = 1;
5935: }
5936: $ansnum += $answers_needed;
5937: }
5938: return $ansnum;
5939: }
5940:
5941: =pod
5942:
5943: =item scantron_add_delay
5944:
5945: Adds an error message that occurred during the grading phase to a
5946: queue of messages to be shown after grading pass is complete
5947:
5948: Arguments:
5949: $delayqueue - arrary ref of hash ref of error messages
5950: $scanline - the scanline that caused the error
5951: $errormesage - the error message
5952: $errorcode - a numeric code for the error
5953:
5954: Side Effects:
5955: updates the $delayqueue to have a new hash ref of the error
5956:
5957: =cut
5958:
5959: sub scantron_add_delay {
5960: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5961: push(@$delayqueue,
5962: {'line' => $scanline, 'emsg' => $errormessage,
5963: 'ecode' => $errorcode }
5964: );
5965: }
5966:
5967: =pod
5968:
5969: =item scantron_find_student
5970:
5971: Finds the username for the current scanline
5972:
5973: Arguments:
5974: $scantron_record - hash result from scantron_parse_scanline
5975: $scan_data - hash of correction information
5976: (see &scantron_getfile() form more information)
5977: $idmap - hash from &username_to_idmap()
5978: $line - number of current scanline
5979:
5980: Returns:
5981: Either 'username:domain' or undef if unknown
5982:
5983: =cut
5984:
5985: sub scantron_find_student {
5986: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5987: my $scanID=$$scantron_record{'scantron.ID'};
5988: if ($scanID =~ /^\s*$/) {
5989: return &scan_data($scan_data,"$line.user");
5990: }
5991: foreach my $id (keys(%$idmap)) {
5992: if (lc($id) eq lc($scanID)) {
5993: return $$idmap{$id};
5994: }
5995: }
5996: return undef;
5997: }
5998:
5999: =pod
6000:
6001: =item scantron_filter
6002:
6003: Filter sub for lonnavmaps, filters out hidden resources if ignore
6004: hidden resources was selected
6005:
6006: =cut
6007:
6008: sub scantron_filter {
6009: my ($curres)=@_;
6010:
6011: if (ref($curres) && $curres->is_problem()) {
6012: # if the user has asked to not have either hidden
6013: # or 'randomout' controlled resources to be graded
6014: # don't include them
6015: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6016: && $curres->randomout) {
6017: return 0;
6018: }
6019: return 1;
6020: }
6021: return 0;
6022: }
6023:
6024: =pod
6025:
6026: =item scantron_process_corrections
6027:
6028: Gets correction information out of submitted form data and corrects
6029: the scanline
6030:
6031: =cut
6032:
6033: sub scantron_process_corrections {
6034: my ($r) = @_;
6035: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6036: my ($scanlines,$scan_data)=&scantron_getfile();
6037: my $classlist=&Apache::loncoursedata::get_classlist();
6038: my $which=$env{'form.scantron_line'};
6039: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6040: my ($skip,$err,$errmsg);
6041: if ($env{'form.scantron_skip_record'}) {
6042: $skip=1;
6043: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6044: my $newstudent=$env{'form.scantron_username'}.':'.
6045: $env{'form.scantron_domain'};
6046: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6047: ($line,$err,$errmsg)=
6048: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6049: 'ID',{'newid'=>$newid,
6050: 'username'=>$env{'form.scantron_username'},
6051: 'domain'=>$env{'form.scantron_domain'}});
6052: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6053: my $resolution=$env{'form.scantron_CODE_resolution'};
6054: my $newCODE;
6055: my %args;
6056: if ($resolution eq 'use_unfound') {
6057: $newCODE='use_unfound';
6058: } elsif ($resolution eq 'use_found') {
6059: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6060: } elsif ($resolution eq 'use_typed') {
6061: $newCODE=$env{'form.scantron_CODE_newvalue'};
6062: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6063: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6064: }
6065: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6066: $args{'CODE_ignore_dup'}=1;
6067: }
6068: $args{'CODE'}=$newCODE;
6069: ($line,$err,$errmsg)=
6070: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6071: 'CODE',\%args);
6072: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6073: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6074: ($line,$err,$errmsg)=
6075: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6076: $which,'answer',
6077: { 'question'=>$question,
6078: 'response'=>$env{"form.scantron_correct_Q_$question"},
6079: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6080: if ($err) { last; }
6081: }
6082: }
6083: if ($err) {
6084: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
6085: } else {
6086: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6087: &scantron_putfile($scanlines,$scan_data);
6088: }
6089: }
6090:
6091: =pod
6092:
6093: =item reset_skipping_status
6094:
6095: Forgets the current set of remember skipped scanlines (and thus
6096: reverts back to considering all lines in the
6097: scantron_skipped_<filename> file)
6098:
6099: =cut
6100:
6101: sub reset_skipping_status {
6102: my ($scanlines,$scan_data)=&scantron_getfile();
6103: &scan_data($scan_data,'remember_skipping',undef,1);
6104: &scantron_putfile(undef,$scan_data);
6105: }
6106:
6107: =pod
6108:
6109: =item start_skipping
6110:
6111: Marks a scanline to be skipped.
6112:
6113: =cut
6114:
6115: sub start_skipping {
6116: my ($scan_data,$i)=@_;
6117: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6118: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6119: $remembered{$i}=2;
6120: } else {
6121: $remembered{$i}=1;
6122: }
6123: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6124: }
6125:
6126: =pod
6127:
6128: =item should_be_skipped
6129:
6130: Checks whether a scanline should be skipped.
6131:
6132: =cut
6133:
6134: sub should_be_skipped {
6135: my ($scanlines,$scan_data,$i)=@_;
6136: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6137: # not redoing old skips
6138: if ($scanlines->{'skipped'}[$i]) { return 1; }
6139: return 0;
6140: }
6141: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6142:
6143: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6144: return 0;
6145: }
6146: return 1;
6147: }
6148:
6149: =pod
6150:
6151: =item remember_current_skipped
6152:
6153: Discovers what scanlines are in the scantron_skipped_<filename>
6154: file and remembers them into scan_data for later use.
6155:
6156: =cut
6157:
6158: sub remember_current_skipped {
6159: my ($scanlines,$scan_data)=&scantron_getfile();
6160: my %to_remember;
6161: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6162: if ($scanlines->{'skipped'}[$i]) {
6163: $to_remember{$i}=1;
6164: }
6165: }
6166:
6167: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6168: &scantron_putfile(undef,$scan_data);
6169: }
6170:
6171: =pod
6172:
6173: =item check_for_error
6174:
6175: Checks if there was an error when attempting to remove a specific
6176: scantron_.. bubble sheet data file. Prints out an error if
6177: something went wrong.
6178:
6179: =cut
6180:
6181: sub check_for_error {
6182: my ($r,$result)=@_;
6183: if ($result ne 'ok' && $result ne 'not_found' ) {
6184: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6185: }
6186: }
6187:
6188: =pod
6189:
6190: =item scantron_warning_screen
6191:
6192: Interstitial screen to make sure the operator has selected the
6193: correct options before we start the validation phase.
6194:
6195: =cut
6196:
6197: sub scantron_warning_screen {
6198: my ($button_text,$symb)=@_;
6199: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6200: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6201: my $CODElist;
6202: if ($scantron_config{'CODElocation'} &&
6203: $scantron_config{'CODEstart'} &&
6204: $scantron_config{'CODElength'}) {
6205: $CODElist=$env{'form.scantron_CODElist'};
6206: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
6207: $CODElist=
6208: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6209: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6210: }
6211: return ('
6212: <p>
6213: <span class="LC_warning">
6214: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
6215: </p>
6216: <table>
6217: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6218: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6219: '.$CODElist.'
6220: </table>
6221: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
6222: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
6223:
6224: <br />
6225: ');
6226: }
6227:
6228: =pod
6229:
6230: =item scantron_do_warning
6231:
6232: Check if the operator has picked something for all required
6233: fields. Error out if something is missing.
6234:
6235: =cut
6236:
6237: sub scantron_do_warning {
6238: my ($r,$symb)=@_;
6239: if (!$symb) {return '';}
6240: my $default_form_data=&defaultFormData($symb);
6241: $r->print(&scantron_form_start().$default_form_data);
6242: if ( $env{'form.selectpage'} eq '' ||
6243: $env{'form.scantron_selectfile'} eq '' ||
6244: $env{'form.scantron_format'} eq '' ) {
6245: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6246: if ( $env{'form.selectpage'} eq '') {
6247: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6248: }
6249: if ( $env{'form.scantron_selectfile'} eq '') {
6250: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
6251: }
6252: if ( $env{'form.scantron_format'} eq '') {
6253: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
6254: }
6255: } else {
6256: my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
6257: $r->print('
6258: '.$warning.'
6259: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6260: <input type="hidden" name="command" value="scantron_validate" />
6261: ');
6262: }
6263: $r->print("</form><br />");
6264: return '';
6265: }
6266:
6267: =pod
6268:
6269: =item scantron_form_start
6270:
6271: html hidden input for remembering all selected grading options
6272:
6273: =cut
6274:
6275: sub scantron_form_start {
6276: my ($max_bubble)=@_;
6277: my $result= <<SCANTRONFORM;
6278: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6279: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6280: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6281: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6282: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6283: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6284: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6285: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6286: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6287: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6288: SCANTRONFORM
6289:
6290: my $line = 0;
6291: while (defined($env{"form.scantron.bubblelines.$line"})) {
6292: my $chunk =
6293: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6294: $chunk .=
6295: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6296: $chunk .=
6297: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6298: $chunk .=
6299: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6300: $result .= $chunk;
6301: $line++;
6302: }
6303: return $result;
6304: }
6305:
6306: =pod
6307:
6308: =item scantron_validate_file
6309:
6310: Dispatch routine for doing validation of a bubble sheet data file.
6311:
6312: Also processes any necessary information resets that need to
6313: occur before validation begins (ignore previous corrections,
6314: restarting the skipped records processing)
6315:
6316: =cut
6317:
6318: sub scantron_validate_file {
6319: my ($r,$symb) = @_;
6320: if (!$symb) {return '';}
6321: my $default_form_data=&defaultFormData($symb);
6322:
6323: # do the detection of only doing skipped records first befroe we delete
6324: # them when doing the corrections reset
6325: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6326: &reset_skipping_status();
6327: }
6328: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6329: &remember_current_skipped();
6330: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6331: }
6332:
6333: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6334: &check_for_error($r,&scantron_remove_file('corrected'));
6335: &check_for_error($r,&scantron_remove_file('skipped'));
6336: &check_for_error($r,&scantron_remove_scan_data());
6337: $env{'form.scantron_options_ignore'}='done';
6338: }
6339:
6340: if ($env{'form.scantron_corrections'}) {
6341: &scantron_process_corrections($r);
6342: }
6343: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6344: #get the student pick code ready
6345: $r->print(&Apache::loncommon::studentbrowser_javascript());
6346: my $nav_error;
6347: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6348: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
6349: if ($nav_error) {
6350: $r->print(&navmap_errormsg());
6351: return '';
6352: }
6353: my $result=&scantron_form_start($max_bubble).$default_form_data;
6354: $r->print($result);
6355:
6356: my @validate_phases=( 'sequence',
6357: 'ID',
6358: 'CODE',
6359: 'doublebubble',
6360: 'missingbubbles');
6361: if (!$env{'form.validatepass'}) {
6362: $env{'form.validatepass'} = 0;
6363: }
6364: my $currentphase=$env{'form.validatepass'};
6365:
6366:
6367: my $stop=0;
6368: while (!$stop && $currentphase < scalar(@validate_phases)) {
6369: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6370: $r->rflush();
6371: my $which="scantron_validate_".$validate_phases[$currentphase];
6372: {
6373: no strict 'refs';
6374: ($stop,$currentphase)=&$which($r,$currentphase);
6375: }
6376: }
6377: if (!$stop) {
6378: my $warning=&scantron_warning_screen('Start Grading',$symb);
6379: $r->print(&mt('Validation process complete.').'<br />'.
6380: $warning.
6381: &mt('Perform verification for each student after storage of submissions?').
6382: ' <span class="LC_nobreak"><label>'.
6383: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6384: (' 'x3).'<label>'.
6385: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6386: '</label></span><br />'.
6387: &mt('Grading will take longer if you use verification.').'<br />'.
6388: &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','»').'<br /><br />'.
6389: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6390: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6391: } else {
6392: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6393: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6394: }
6395: if ($stop) {
6396: if ($validate_phases[$currentphase] eq 'sequence') {
6397: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6398: $r->print(' '.&mt('this error').' <br />');
6399:
6400: $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
6401: } else {
6402: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6403: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6404: } else {
6405: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6406: }
6407: $r->print(' '.&mt('using corrected info').' <br />');
6408: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6409: $r->print(" ".&mt("this scanline saving it for later."));
6410: }
6411: }
6412: $r->print(" </form><br />");
6413: return '';
6414: }
6415:
6416:
6417: =pod
6418:
6419: =item scantron_remove_file
6420:
6421: Removes the requested bubble sheet data file, makes sure that
6422: scantron_original_<filename> is never removed
6423:
6424:
6425: =cut
6426:
6427: sub scantron_remove_file {
6428: my ($which)=@_;
6429: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6430: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6431: my $file='scantron_';
6432: if ($which eq 'corrected' || $which eq 'skipped') {
6433: $file.=$which.'_';
6434: } else {
6435: return 'refused';
6436: }
6437: $file.=$env{'form.scantron_selectfile'};
6438: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6439: }
6440:
6441:
6442: =pod
6443:
6444: =item scantron_remove_scan_data
6445:
6446: Removes all scan_data correction for the requested bubble sheet
6447: data file. (In the case that both the are doing skipped records we need
6448: to remember the old skipped lines for the time being so that element
6449: persists for a while.)
6450:
6451: =cut
6452:
6453: sub scantron_remove_scan_data {
6454: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6455: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6456: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6457: my @todelete;
6458: my $filename=$env{'form.scantron_selectfile'};
6459: foreach my $key (@keys) {
6460: if ($key=~/^\Q$filename\E_/) {
6461: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6462: $key=~/remember_skipping/) {
6463: next;
6464: }
6465: push(@todelete,$key);
6466: }
6467: }
6468: my $result;
6469: if (@todelete) {
6470: $result = &Apache::lonnet::del('nohist_scantrondata',
6471: \@todelete,$cdom,$cname);
6472: } else {
6473: $result = 'ok';
6474: }
6475: return $result;
6476: }
6477:
6478:
6479: =pod
6480:
6481: =item scantron_getfile
6482:
6483: Fetches the requested bubble sheet data file (all 3 versions), and
6484: the scan_data hash
6485:
6486: Arguments:
6487: None
6488:
6489: Returns:
6490: 2 hash references
6491:
6492: - first one has
6493: orig -
6494: corrected -
6495: skipped - each of which points to an array ref of the specified
6496: file broken up into individual lines
6497: count - number of scanlines
6498:
6499: - second is the scan_data hash possible keys are
6500: ($number refers to scanline numbered $number and thus the key affects
6501: only that scanline
6502: $bubline refers to the specific bubble line element and the aspects
6503: refers to that specific bubble line element)
6504:
6505: $number.user - username:domain to use
6506: $number.CODE_ignore_dup
6507: - ignore the duplicate CODE error
6508: $number.useCODE
6509: - use the CODE in the scanline as is
6510: $number.no_bubble.$bubline
6511: - it is valid that there is no bubbled in bubble
6512: at $number $bubline
6513: remember_skipping
6514: - a frozen hash containing keys of $number and values
6515: of either
6516: 1 - we are on a 'do skipped records pass' and plan
6517: on processing this line
6518: 2 - we are on a 'do skipped records pass' and this
6519: scanline has been marked to skip yet again
6520:
6521: =cut
6522:
6523: sub scantron_getfile {
6524: #FIXME really would prefer a scantron directory
6525: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6526: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6527: my $lines;
6528: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6529: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6530: my %scanlines;
6531: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6532: my $temp=$scanlines{'orig'};
6533: $scanlines{'count'}=$#$temp;
6534:
6535: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6536: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6537: if ($lines eq '-1') {
6538: $scanlines{'corrected'}=[];
6539: } else {
6540: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6541: }
6542: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6543: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6544: if ($lines eq '-1') {
6545: $scanlines{'skipped'}=[];
6546: } else {
6547: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6548: }
6549: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6550: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6551: my %scan_data = @tmp;
6552: return (\%scanlines,\%scan_data);
6553: }
6554:
6555: =pod
6556:
6557: =item lonnet_putfile
6558:
6559: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6560:
6561: Arguments:
6562: $contents - data to store
6563: $filename - filename to store $contents into
6564:
6565: Returns:
6566: result value from &Apache::lonnet::finishuserfileupload
6567:
6568: =cut
6569:
6570: sub lonnet_putfile {
6571: my ($contents,$filename)=@_;
6572: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6573: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6574: $env{'form.sillywaytopassafilearound'}=$contents;
6575: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6576:
6577: }
6578:
6579: =pod
6580:
6581: =item scantron_putfile
6582:
6583: Stores the current version of the bubble sheet data files, and the
6584: scan_data hash. (Does not modify the original version only the
6585: corrected and skipped versions.
6586:
6587: Arguments:
6588: $scanlines - hash ref that looks like the first return value from
6589: &scantron_getfile()
6590: $scan_data - hash ref that looks like the second return value from
6591: &scantron_getfile()
6592:
6593: =cut
6594:
6595: sub scantron_putfile {
6596: my ($scanlines,$scan_data) = @_;
6597: #FIXME really would prefer a scantron directory
6598: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6599: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6600: if ($scanlines) {
6601: my $prefix='scantron_';
6602: # no need to update orig, shouldn't change
6603: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6604: # $env{'form.scantron_selectfile'});
6605: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6606: $prefix.'corrected_'.
6607: $env{'form.scantron_selectfile'});
6608: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6609: $prefix.'skipped_'.
6610: $env{'form.scantron_selectfile'});
6611: }
6612: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6613: }
6614:
6615: =pod
6616:
6617: =item scantron_get_line
6618:
6619: Returns the correct version of the scanline
6620:
6621: Arguments:
6622: $scanlines - hash ref that looks like the first return value from
6623: &scantron_getfile()
6624: $scan_data - hash ref that looks like the second return value from
6625: &scantron_getfile()
6626: $i - number of the requested line (starts at 0)
6627:
6628: Returns:
6629: A scanline, (either the original or the corrected one if it
6630: exists), or undef if the requested scanline should be
6631: skipped. (Either because it's an skipped scanline, or it's an
6632: unskipped scanline and we are not doing a 'do skipped scanlines'
6633: pass.
6634:
6635: =cut
6636:
6637: sub scantron_get_line {
6638: my ($scanlines,$scan_data,$i)=@_;
6639: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6640: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6641: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6642: return $scanlines->{'orig'}[$i];
6643: }
6644:
6645: =pod
6646:
6647: =item scantron_todo_count
6648:
6649: Counts the number of scanlines that need processing.
6650:
6651: Arguments:
6652: $scanlines - hash ref that looks like the first return value from
6653: &scantron_getfile()
6654: $scan_data - hash ref that looks like the second return value from
6655: &scantron_getfile()
6656:
6657: Returns:
6658: $count - number of scanlines to process
6659:
6660: =cut
6661:
6662: sub get_todo_count {
6663: my ($scanlines,$scan_data)=@_;
6664: my $count=0;
6665: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6666: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6667: if ($line=~/^[\s\cz]*$/) { next; }
6668: $count++;
6669: }
6670: return $count;
6671: }
6672:
6673: =pod
6674:
6675: =item scantron_put_line
6676:
6677: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6678: data file.
6679:
6680: Arguments:
6681: $scanlines - hash ref that looks like the first return value from
6682: &scantron_getfile()
6683: $scan_data - hash ref that looks like the second return value from
6684: &scantron_getfile()
6685: $i - line number to update
6686: $newline - contents of the updated scanline
6687: $skip - if true make the line for skipping and update the
6688: 'skipped' file
6689:
6690: =cut
6691:
6692: sub scantron_put_line {
6693: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6694: if ($skip) {
6695: $scanlines->{'skipped'}[$i]=$newline;
6696: &start_skipping($scan_data,$i);
6697: return;
6698: }
6699: $scanlines->{'corrected'}[$i]=$newline;
6700: }
6701:
6702: =pod
6703:
6704: =item scantron_clear_skip
6705:
6706: Remove a line from the 'skipped' file
6707:
6708: Arguments:
6709: $scanlines - hash ref that looks like the first return value from
6710: &scantron_getfile()
6711: $scan_data - hash ref that looks like the second return value from
6712: &scantron_getfile()
6713: $i - line number to update
6714:
6715: =cut
6716:
6717: sub scantron_clear_skip {
6718: my ($scanlines,$scan_data,$i)=@_;
6719: if (exists($scanlines->{'skipped'}[$i])) {
6720: undef($scanlines->{'skipped'}[$i]);
6721: return 1;
6722: }
6723: return 0;
6724: }
6725:
6726: =pod
6727:
6728: =item scantron_filter_not_exam
6729:
6730: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6731: filter out resources that are not marked as 'exam' mode
6732:
6733: =cut
6734:
6735: sub scantron_filter_not_exam {
6736: my ($curres)=@_;
6737:
6738: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6739: # if the user has asked to not have either hidden
6740: # or 'randomout' controlled resources to be graded
6741: # don't include them
6742: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6743: && $curres->randomout) {
6744: return 0;
6745: }
6746: return 1;
6747: }
6748: return 0;
6749: }
6750:
6751: =pod
6752:
6753: =item scantron_validate_sequence
6754:
6755: Validates the selected sequence, checking for resource that are
6756: not set to exam mode.
6757:
6758: =cut
6759:
6760: sub scantron_validate_sequence {
6761: my ($r,$currentphase) = @_;
6762:
6763: my $navmap=Apache::lonnavmaps::navmap->new();
6764: unless (ref($navmap)) {
6765: $r->print(&navmap_errormsg());
6766: return (1,$currentphase);
6767: }
6768: my (undef,undef,$sequence)=
6769: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6770:
6771: my $map=$navmap->getResourceByUrl($sequence);
6772:
6773: $r->print('<input type="hidden" name="validate_sequence_exam"
6774: value="ignore" />');
6775: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6776: my @resources=
6777: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6778: if (@resources) {
6779: $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>");
6780: return (1,$currentphase);
6781: }
6782: }
6783:
6784: return (0,$currentphase+1);
6785: }
6786:
6787:
6788:
6789: sub scantron_validate_ID {
6790: my ($r,$currentphase) = @_;
6791:
6792: #get student info
6793: my $classlist=&Apache::loncoursedata::get_classlist();
6794: my %idmap=&username_to_idmap($classlist);
6795:
6796: #get scantron line setup
6797: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6798: my ($scanlines,$scan_data)=&scantron_getfile();
6799:
6800: my $nav_error;
6801: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
6802: if ($nav_error) {
6803: $r->print(&navmap_errormsg());
6804: return(1,$currentphase);
6805: }
6806:
6807: my %found=('ids'=>{},'usernames'=>{});
6808: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6809: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6810: if ($line=~/^[\s\cz]*$/) { next; }
6811: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6812: $scan_data);
6813: my $id=$$scan_record{'scantron.ID'};
6814: my $found;
6815: foreach my $checkid (keys(%idmap)) {
6816: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6817: }
6818: if ($found) {
6819: my $username=$idmap{$found};
6820: if ($found{'ids'}{$found}) {
6821: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6822: $line,'duplicateID',$found);
6823: return(1,$currentphase);
6824: } elsif ($found{'usernames'}{$username}) {
6825: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6826: $line,'duplicateID',$username);
6827: return(1,$currentphase);
6828: }
6829: #FIXME store away line we previously saw the ID on to use above
6830: $found{'ids'}{$found}++;
6831: $found{'usernames'}{$username}++;
6832: } else {
6833: if ($id =~ /^\s*$/) {
6834: my $username=&scan_data($scan_data,"$i.user");
6835: if (defined($username) && $found{'usernames'}{$username}) {
6836: &scantron_get_correction($r,$i,$scan_record,
6837: \%scantron_config,
6838: $line,'duplicateID',$username);
6839: return(1,$currentphase);
6840: } elsif (!defined($username)) {
6841: &scantron_get_correction($r,$i,$scan_record,
6842: \%scantron_config,
6843: $line,'incorrectID');
6844: return(1,$currentphase);
6845: }
6846: $found{'usernames'}{$username}++;
6847: } else {
6848: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6849: $line,'incorrectID');
6850: return(1,$currentphase);
6851: }
6852: }
6853: }
6854:
6855: return (0,$currentphase+1);
6856: }
6857:
6858:
6859: sub scantron_get_correction {
6860: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6861: #FIXME in the case of a duplicated ID the previous line, probably need
6862: #to show both the current line and the previous one and allow skipping
6863: #the previous one or the current one
6864:
6865: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6866: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6867: " for PaperID <tt>[_1]</tt>",
6868: $$scan_record{'scantron.PaperID'})."</p> \n");
6869: } else {
6870: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6871: " in scanline [_1] <pre>[_2]</pre>",
6872: $i,$line)."</p> \n");
6873: }
6874: my $message="<p>".&mt("The ID on the form is <tt>[_1]</tt><br />".
6875: "The name on the paper is [_2],[_3]",
6876: $$scan_record{'scantron.ID'},
6877: $$scan_record{'scantron.LastName'},
6878: $$scan_record{'scantron.FirstName'})."</p>";
6879:
6880: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6881: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6882: # Array populated for doublebubble or
6883: my @lines_to_correct; # missingbubble errors to build javascript
6884: # to validate radio button checking
6885:
6886: if ($error =~ /ID$/) {
6887: if ($error eq 'incorrectID') {
6888: $r->print("<p>".&mt("The encoded ID is not in the classlist").
6889: "</p>\n");
6890: } elsif ($error eq 'duplicateID') {
6891: $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
6892: }
6893: $r->print($message);
6894: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6895: $r->print("\n<ul><li> ");
6896: #FIXME it would be nice if this sent back the user ID and
6897: #could do partial userID matches
6898: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6899: 'scantron_username','scantron_domain'));
6900: $r->print(": <input type='text' name='scantron_username' value='' />");
6901: $r->print("\n@".
6902: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6903:
6904: $r->print('</li>');
6905: } elsif ($error =~ /CODE$/) {
6906: if ($error eq 'incorrectCODE') {
6907: $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
6908: } elsif ($error eq 'duplicateCODE') {
6909: $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");
6910: }
6911: $r->print("<p>".&mt("The CODE on the form is <tt>'[_1]'</tt>",
6912: $$scan_record{'scantron.CODE'})."<br />\n");
6913: $r->print($message);
6914: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6915: $r->print("\n<br /> ");
6916: my $i=0;
6917: if ($error eq 'incorrectCODE'
6918: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6919: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6920: if ($closest > 0) {
6921: foreach my $testcode (@{$closest}) {
6922: my $checked='';
6923: if (!$i) { $checked=' checked="checked"'; }
6924: $r->print("
6925: <label>
6926: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
6927: ".&mt("Use the similar CODE [_1] instead.",
6928: "<b><tt>".$testcode."</tt></b>")."
6929: </label>
6930: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
6931: $r->print("\n<br />");
6932: $i++;
6933: }
6934: }
6935: }
6936: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6937: my $checked; if (!$i) { $checked=' checked="checked"'; }
6938: $r->print("
6939: <label>
6940: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
6941: ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
6942: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
6943: </label>");
6944: $r->print("\n<br />");
6945: }
6946:
6947: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
6948: function change_radio(field) {
6949: var slct=document.scantronupload.scantron_CODE_resolution;
6950: var i;
6951: for (i=0;i<slct.length;i++) {
6952: if (slct[i].value==field) { slct[i].checked=true; }
6953: }
6954: }
6955: ENDSCRIPT
6956: my $href="/adm/pickcode?".
6957: "form=".&escape("scantronupload").
6958: "&scantron_format=".&escape($env{'form.scantron_format'}).
6959: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6960: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6961: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6962: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6963: $r->print("
6964: <label>
6965: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
6966: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
6967: "<a target='_blank' href='$href'>","</a>")."
6968: </label>
6969: ".&mt("Selected CODE is [_1]",'<input readonly="readonly" type="text" size="8" name="scantron_CODE_selectedvalue" onfocus="javascript:change_radio(\'use_found\')" onchange="javascript:change_radio(\'use_found\')" />'));
6970: $r->print("\n<br />");
6971: }
6972: $r->print("
6973: <label>
6974: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
6975: ".&mt("Use [_1] as the CODE.",
6976: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
6977: $r->print("\n<br /><br />");
6978: } elsif ($error eq 'doublebubble') {
6979: $r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
6980:
6981: # The form field scantron_questions is acutally a list of line numbers.
6982: # represented by this form so:
6983:
6984: my $line_list = &questions_to_line_list($arg);
6985:
6986: $r->print('<input type="hidden" name="scantron_questions" value="'.
6987: $line_list.'" />');
6988: $r->print($message);
6989: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
6990: foreach my $question (@{$arg}) {
6991: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6992: $scan_record, $error);
6993: push(@lines_to_correct,@linenums);
6994: }
6995: $r->print(&verify_bubbles_checked(@lines_to_correct));
6996: } elsif ($error eq 'missingbubble') {
6997: $r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
6998: $r->print($message);
6999: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7000: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7001:
7002: # The form field scantron_questions is actually a list of line numbers not
7003: # a list of question numbers. Therefore:
7004: #
7005:
7006: my $line_list = &questions_to_line_list($arg);
7007:
7008: $r->print('<input type="hidden" name="scantron_questions" value="'.
7009: $line_list.'" />');
7010: foreach my $question (@{$arg}) {
7011: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7012: $scan_record, $error);
7013: push(@lines_to_correct,@linenums);
7014: }
7015: $r->print(&verify_bubbles_checked(@lines_to_correct));
7016: } else {
7017: $r->print("\n<ul>");
7018: }
7019: $r->print("\n</li></ul>");
7020: }
7021:
7022: sub verify_bubbles_checked {
7023: my (@ansnums) = @_;
7024: my $ansnumstr = join('","',@ansnums);
7025: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7026: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
7027: function verify_bubble_radio(form) {
7028: var ansnumArray = new Array ("$ansnumstr");
7029: var need_bubble_count = 0;
7030: for (var i=0; i<ansnumArray.length; i++) {
7031: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7032: var bubble_picked = 0;
7033: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7034: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7035: bubble_picked = 1;
7036: }
7037: }
7038: if (bubble_picked == 0) {
7039: need_bubble_count ++;
7040: }
7041: }
7042: }
7043: if (need_bubble_count) {
7044: alert("$warning");
7045: return;
7046: }
7047: form.submit();
7048: }
7049: ENDSCRIPT
7050: return $output;
7051: }
7052:
7053: =pod
7054:
7055: =item questions_to_line_list
7056:
7057: Converts a list of questions into a string of comma separated
7058: line numbers in the answer sheet used by the questions. This is
7059: used to fill in the scantron_questions form field.
7060:
7061: Arguments:
7062: questions - Reference to an array of questions.
7063:
7064: =cut
7065:
7066:
7067: sub questions_to_line_list {
7068: my ($questions) = @_;
7069: my @lines;
7070:
7071: foreach my $item (@{$questions}) {
7072: my $question = $item;
7073: my ($first,$count,$last);
7074: if ($item =~ /^(\d+)\.(\d+)$/) {
7075: $question = $1;
7076: my $subquestion = $2;
7077: $first = $first_bubble_line{$question-1} + 1;
7078: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7079: my $subcount = 1;
7080: while ($subcount<$subquestion) {
7081: $first += $subans[$subcount-1];
7082: $subcount ++;
7083: }
7084: $count = $subans[$subquestion-1];
7085: } else {
7086: $first = $first_bubble_line{$question-1} + 1;
7087: $count = $bubble_lines_per_response{$question-1};
7088: }
7089: $last = $first+$count-1;
7090: push(@lines, ($first..$last));
7091: }
7092: return join(',', @lines);
7093: }
7094:
7095: =pod
7096:
7097: =item prompt_for_corrections
7098:
7099: Prompts for a potentially multiline correction to the
7100: user's bubbling (factors out common code from scantron_get_correction
7101: for multi and missing bubble cases).
7102:
7103: Arguments:
7104: $r - Apache request object.
7105: $question - The question number to prompt for.
7106: $scan_config - The scantron file configuration hash.
7107: $scan_record - Reference to the hash that has the the parsed scanlines.
7108: $error - Type of error
7109:
7110: Implicit inputs:
7111: %bubble_lines_per_response - Starting line numbers for each question.
7112: Numbered from 0 (but question numbers are from
7113: 1.
7114: %first_bubble_line - Starting bubble line for each question.
7115: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7116: type problems render as separate sub-questions,
7117: in exam mode. This hash contains a
7118: comma-separated list of the lines per
7119: sub-question.
7120: %responsetype_per_response - essayresponse, formularesponse,
7121: stringresponse, imageresponse, reactionresponse,
7122: and organicresponse type problem parts can have
7123: multiple lines per response if the weight
7124: assigned exceeds 10. In this case, only
7125: one bubble per line is permitted, but more
7126: than one line might contain bubbles, e.g.
7127: bubbling of: line 1 - J, line 2 - J,
7128: line 3 - B would assign 22 points.
7129:
7130: =cut
7131:
7132: sub prompt_for_corrections {
7133: my ($r, $question, $scan_config, $scan_record, $error) = @_;
7134: my ($current_line,$lines);
7135: my @linenums;
7136: my $questionnum = $question;
7137: if ($question =~ /^(\d+)\.(\d+)$/) {
7138: $question = $1;
7139: $current_line = $first_bubble_line{$question-1} + 1 ;
7140: my $subquestion = $2;
7141: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7142: my $subcount = 1;
7143: while ($subcount<$subquestion) {
7144: $current_line += $subans[$subcount-1];
7145: $subcount ++;
7146: }
7147: $lines = $subans[$subquestion-1];
7148: } else {
7149: $current_line = $first_bubble_line{$question-1} + 1 ;
7150: $lines = $bubble_lines_per_response{$question-1};
7151: }
7152: if ($lines > 1) {
7153: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7154: if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
7155: ($responsetype_per_response{$question-1} eq 'formularesponse') ||
7156: ($responsetype_per_response{$question-1} eq 'stringresponse') ||
7157: ($responsetype_per_response{$question-1} eq 'imageresponse') ||
7158: ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
7159: ($responsetype_per_response{$question-1} eq 'organicresponse')) {
7160: $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
7161: } else {
7162: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7163: }
7164: }
7165: for (my $i =0; $i < $lines; $i++) {
7166: my $selected = $$scan_record{"scantron.$current_line.answer"};
7167: &scantron_bubble_selector($r,$scan_config,$current_line,
7168: $questionnum,$error,split('', $selected));
7169: push(@linenums,$current_line);
7170: $current_line++;
7171: }
7172: if ($lines > 1) {
7173: $r->print("<hr /><br />");
7174: }
7175: return @linenums;
7176: }
7177:
7178: =pod
7179:
7180: =item scantron_bubble_selector
7181:
7182: Generates the html radiobuttons to correct a single bubble line
7183: possibly showing the existing the selected bubbles if known
7184:
7185: Arguments:
7186: $r - Apache request object
7187: $scan_config - hash from &get_scantron_config()
7188: $line - Number of the line being displayed.
7189: $questionnum - Question number (may include subquestion)
7190: $error - Type of error.
7191: @selected - Array of bubbles picked on this line.
7192:
7193: =cut
7194:
7195: sub scantron_bubble_selector {
7196: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7197: my $max=$$scan_config{'Qlength'};
7198:
7199: my $scmode=$$scan_config{'Qon'};
7200: if ($scmode eq 'number' || $scmode eq 'letter') {
7201: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
7202: ($$scan_config{'BubblesPerRow'} > 0)) {
7203: $max=$$scan_config{'BubblesPerRow'};
7204: if (($scmode eq 'number') && ($max > 10)) {
7205: $max = 10;
7206: } elsif (($scmode eq 'letter') && $max > 26) {
7207: $max = 26;
7208: }
7209: } else {
7210: $max = 10;
7211: }
7212: }
7213:
7214: my @alphabet=('A'..'Z');
7215: $r->print(&Apache::loncommon::start_data_table().
7216: &Apache::loncommon::start_data_table_row());
7217: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7218: for (my $i=0;$i<$max+1;$i++) {
7219: $r->print("\n".'<td align="center">');
7220: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7221: else { $r->print(' '); }
7222: $r->print('</td>');
7223: }
7224: $r->print(&Apache::loncommon::end_data_table_row().
7225: &Apache::loncommon::start_data_table_row());
7226: for (my $i=0;$i<$max;$i++) {
7227: $r->print("\n".
7228: '<td><label><input type="radio" name="scantron_correct_Q_'.
7229: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7230: }
7231: my $nobub_checked = ' ';
7232: if ($error eq 'missingbubble') {
7233: $nobub_checked = ' checked = "checked" ';
7234: }
7235: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7236: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7237: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7238: $line.'" value="'.$questionnum.'" /></td>');
7239: $r->print(&Apache::loncommon::end_data_table_row().
7240: &Apache::loncommon::end_data_table());
7241: }
7242:
7243: =pod
7244:
7245: =item num_matches
7246:
7247: Counts the number of characters that are the same between the two arguments.
7248:
7249: Arguments:
7250: $orig - CODE from the scanline
7251: $code - CODE to match against
7252:
7253: Returns:
7254: $count - integer count of the number of same characters between the
7255: two arguments
7256:
7257: =cut
7258:
7259: sub num_matches {
7260: my ($orig,$code) = @_;
7261: my @code=split(//,$code);
7262: my @orig=split(//,$orig);
7263: my $same=0;
7264: for (my $i=0;$i<scalar(@code);$i++) {
7265: if ($code[$i] eq $orig[$i]) { $same++; }
7266: }
7267: return $same;
7268: }
7269:
7270: =pod
7271:
7272: =item scantron_get_closely_matching_CODEs
7273:
7274: Cycles through all CODEs and finds the set that has the greatest
7275: number of same characters as the provided CODE
7276:
7277: Arguments:
7278: $allcodes - hash ref returned by &get_codes()
7279: $CODE - CODE from the current scanline
7280:
7281: Returns:
7282: 2 element list
7283: - first elements is number of how closely matching the best fit is
7284: (5 means best set has 5 matching characters)
7285: - second element is an arrary ref containing the set of valid CODEs
7286: that best fit the passed in CODE
7287:
7288: =cut
7289:
7290: sub scantron_get_closely_matching_CODEs {
7291: my ($allcodes,$CODE)=@_;
7292: my @CODEs;
7293: foreach my $testcode (sort(keys(%{$allcodes}))) {
7294: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7295: }
7296:
7297: return ($#CODEs,$CODEs[-1]);
7298: }
7299:
7300: =pod
7301:
7302: =item get_codes
7303:
7304: Builds a hash which has keys of all of the valid CODEs from the selected
7305: set of remembered CODEs.
7306:
7307: Arguments:
7308: $old_name - name of the set of remembered CODEs
7309: $cdom - domain of the course
7310: $cnum - internal course name
7311:
7312: Returns:
7313: %allcodes - keys are the valid CODEs, values are all 1
7314:
7315: =cut
7316:
7317: sub get_codes {
7318: my ($old_name, $cdom, $cnum) = @_;
7319: if (!$old_name) {
7320: $old_name=$env{'form.scantron_CODElist'};
7321: }
7322: if (!$cdom) {
7323: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7324: }
7325: if (!$cnum) {
7326: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7327: }
7328: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7329: $cdom,$cnum);
7330: my %allcodes;
7331: if ($result{"type\0$old_name"} eq 'number') {
7332: %allcodes=map {($_,1)} split(',',$result{$old_name});
7333: } else {
7334: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7335: }
7336: return %allcodes;
7337: }
7338:
7339: =pod
7340:
7341: =item scantron_validate_CODE
7342:
7343: Validates all scanlines in the selected file to not have any
7344: invalid or underspecified CODEs and that none of the codes are
7345: duplicated if this was requested.
7346:
7347: =cut
7348:
7349: sub scantron_validate_CODE {
7350: my ($r,$currentphase) = @_;
7351: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7352: if ($scantron_config{'CODElocation'} &&
7353: $scantron_config{'CODEstart'} &&
7354: $scantron_config{'CODElength'}) {
7355: if (!defined($env{'form.scantron_CODElist'})) {
7356: &FIXME_blow_up()
7357: }
7358: } else {
7359: return (0,$currentphase+1);
7360: }
7361:
7362: my %usedCODEs;
7363:
7364: my %allcodes=&get_codes();
7365:
7366: my $nav_error;
7367: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
7368: if ($nav_error) {
7369: $r->print(&navmap_errormsg());
7370: return(1,$currentphase);
7371: }
7372:
7373: my ($scanlines,$scan_data)=&scantron_getfile();
7374: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7375: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7376: if ($line=~/^[\s\cz]*$/) { next; }
7377: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7378: $scan_data);
7379: my $CODE=$$scan_record{'scantron.CODE'};
7380: my $error=0;
7381: if (!&Apache::lonnet::validCODE($CODE)) {
7382: &scantron_get_correction($r,$i,$scan_record,
7383: \%scantron_config,
7384: $line,'incorrectCODE',\%allcodes);
7385: return(1,$currentphase);
7386: }
7387: if (%allcodes && !exists($allcodes{$CODE})
7388: && !$$scan_record{'scantron.useCODE'}) {
7389: &scantron_get_correction($r,$i,$scan_record,
7390: \%scantron_config,
7391: $line,'incorrectCODE',\%allcodes);
7392: return(1,$currentphase);
7393: }
7394: if (exists($usedCODEs{$CODE})
7395: && $env{'form.scantron_CODEunique'} eq 'yes'
7396: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7397: &scantron_get_correction($r,$i,$scan_record,
7398: \%scantron_config,
7399: $line,'duplicateCODE',$usedCODEs{$CODE});
7400: return(1,$currentphase);
7401: }
7402: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7403: }
7404: return (0,$currentphase+1);
7405: }
7406:
7407: =pod
7408:
7409: =item scantron_validate_doublebubble
7410:
7411: Validates all scanlines in the selected file to not have any
7412: bubble lines with multiple bubbles marked.
7413:
7414: =cut
7415:
7416: sub scantron_validate_doublebubble {
7417: my ($r,$currentphase) = @_;
7418: #get student info
7419: my $classlist=&Apache::loncoursedata::get_classlist();
7420: my %idmap=&username_to_idmap($classlist);
7421:
7422: #get scantron line setup
7423: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7424: my ($scanlines,$scan_data)=&scantron_getfile();
7425: my $nav_error;
7426: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
7427: if ($nav_error) {
7428: $r->print(&navmap_errormsg());
7429: return(1,$currentphase);
7430: }
7431:
7432: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7433: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7434: if ($line=~/^[\s\cz]*$/) { next; }
7435: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7436: $scan_data);
7437: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7438: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7439: 'doublebubble',
7440: $$scan_record{'scantron.doubleerror'});
7441: return (1,$currentphase);
7442: }
7443: return (0,$currentphase+1);
7444: }
7445:
7446:
7447: sub scantron_get_maxbubble {
7448: my ($nav_error,$scantron_config) = @_;
7449: if (defined($env{'form.scantron_maxbubble'}) &&
7450: $env{'form.scantron_maxbubble'}) {
7451: &restore_bubble_lines();
7452: return $env{'form.scantron_maxbubble'};
7453: }
7454:
7455: my (undef, undef, $sequence) =
7456: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7457:
7458: my $navmap=Apache::lonnavmaps::navmap->new();
7459: unless (ref($navmap)) {
7460: if (ref($nav_error)) {
7461: $$nav_error = 1;
7462: }
7463: return;
7464: }
7465: my $map=$navmap->getResourceByUrl($sequence);
7466: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7467: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
7468:
7469: &Apache::lonxml::clear_problem_counter();
7470:
7471: my $uname = $env{'user.name'};
7472: my $udom = $env{'user.domain'};
7473: my $cid = $env{'request.course.id'};
7474: my $total_lines = 0;
7475: %bubble_lines_per_response = ();
7476: %first_bubble_line = ();
7477: %subdivided_bubble_lines = ();
7478: %responsetype_per_response = ();
7479:
7480: my $response_number = 0;
7481: my $bubble_line = 0;
7482: foreach my $resource (@resources) {
7483: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
7484: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
7485: foreach my $part_id (@{$parts}) {
7486: my $lines;
7487:
7488: # TODO - make this a persistent hash not an array.
7489:
7490: # optionresponse, matchresponse and rankresponse type items
7491: # render as separate sub-questions in exam mode.
7492: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
7493: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
7494: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
7495: my ($numbub,$numshown);
7496: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
7497: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
7498: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
7499: }
7500: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
7501: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
7502: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
7503: }
7504: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
7505: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
7506: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
7507: }
7508: }
7509: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
7510: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
7511: }
7512: my $bubbles_per_row =
7513: &bubblesheet_bubbles_per_row($scantron_config);
7514: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
7515: if (($numbub % $bubbles_per_row) != 0) {
7516: $inner_bubble_lines++;
7517: }
7518: for (my $i=0; $i<$numshown; $i++) {
7519: $subdivided_bubble_lines{$response_number} .=
7520: $inner_bubble_lines.',';
7521: }
7522: $subdivided_bubble_lines{$response_number} =~ s/,$//;
7523: $lines = $numshown * $inner_bubble_lines;
7524: } else {
7525: $lines = $analysis->{"$part_id.bubble_lines"};
7526: }
7527:
7528: $first_bubble_line{$response_number} = $bubble_line;
7529: $bubble_lines_per_response{$response_number} = $lines;
7530: $responsetype_per_response{$response_number} =
7531: $analysis->{$part_id.'.type'};
7532: $response_number++;
7533:
7534: $bubble_line += $lines;
7535: $total_lines += $lines;
7536: }
7537: }
7538: }
7539: &Apache::lonnet::delenv('scantron.');
7540:
7541: &save_bubble_lines();
7542: $env{'form.scantron_maxbubble'} =
7543: $total_lines;
7544: return $env{'form.scantron_maxbubble'};
7545: }
7546:
7547: sub bubblesheet_bubbles_per_row {
7548: my ($scantron_config) = @_;
7549: my $bubbles_per_row;
7550: if (ref($scantron_config) eq 'HASH') {
7551: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
7552: }
7553: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
7554: $bubbles_per_row = 10;
7555: }
7556: return $bubbles_per_row;
7557: }
7558:
7559: sub scantron_validate_missingbubbles {
7560: my ($r,$currentphase) = @_;
7561: #get student info
7562: my $classlist=&Apache::loncoursedata::get_classlist();
7563: my %idmap=&username_to_idmap($classlist);
7564:
7565: #get scantron line setup
7566: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7567: my ($scanlines,$scan_data)=&scantron_getfile();
7568: my $nav_error;
7569: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
7570: if ($nav_error) {
7571: return(1,$currentphase);
7572: }
7573: if (!$max_bubble) { $max_bubble=2**31; }
7574: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7575: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7576: if ($line=~/^[\s\cz]*$/) { next; }
7577: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7578: $scan_data);
7579: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
7580: my @to_correct;
7581:
7582: # Probably here's where the error is...
7583:
7584: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
7585: my $lastbubble;
7586: if ($missing =~ /^(\d+)\.(\d+)$/) {
7587: my $question = $1;
7588: my $subquestion = $2;
7589: if (!defined($first_bubble_line{$question -1})) { next; }
7590: my $first = $first_bubble_line{$question-1};
7591: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7592: my $subcount = 1;
7593: while ($subcount<$subquestion) {
7594: $first += $subans[$subcount-1];
7595: $subcount ++;
7596: }
7597: my $count = $subans[$subquestion-1];
7598: $lastbubble = $first + $count;
7599: } else {
7600: if (!defined($first_bubble_line{$missing - 1})) { next; }
7601: $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
7602: }
7603: if ($lastbubble > $max_bubble) { next; }
7604: push(@to_correct,$missing);
7605: }
7606: if (@to_correct) {
7607: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7608: $line,'missingbubble',\@to_correct);
7609: return (1,$currentphase);
7610: }
7611:
7612: }
7613: return (0,$currentphase+1);
7614: }
7615:
7616:
7617: sub scantron_process_students {
7618: my ($r,$symb) = @_;
7619:
7620: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
7621: if (!$symb) {
7622: return '';
7623: }
7624: my $default_form_data=&defaultFormData($symb);
7625:
7626: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7627: my $bubbles_per_row =
7628: &bubblesheet_bubbles_per_row(\%scantron_config);
7629: my ($scanlines,$scan_data)=&scantron_getfile();
7630: my $classlist=&Apache::loncoursedata::get_classlist();
7631: my %idmap=&username_to_idmap($classlist);
7632: my $navmap=Apache::lonnavmaps::navmap->new();
7633: unless (ref($navmap)) {
7634: $r->print(&navmap_errormsg());
7635: return '';
7636: }
7637: my $map=$navmap->getResourceByUrl($sequence);
7638: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7639: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
7640: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7641: \%grader_randomlists_by_symb,$bubbles_per_row);
7642: my $resource_error;
7643: foreach my $resource (@resources) {
7644: my $ressymb;
7645: if (ref($resource)) {
7646: $ressymb = $resource->symb();
7647: } else {
7648: $resource_error = 1;
7649: last;
7650: }
7651: my ($analysis,$parts) =
7652: &scantron_partids_tograde($resource,$env{'request.course.id'},
7653: $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
7654: $grader_partids_by_symb{$ressymb} = $parts;
7655: if (ref($analysis) eq 'HASH') {
7656: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7657: $grader_randomlists_by_symb{$ressymb} =
7658: $analysis->{'parts_withrandomlist'};
7659: }
7660: }
7661: }
7662: if ($resource_error) {
7663: $r->print(&navmap_errormsg());
7664: return '';
7665: }
7666:
7667: my ($uname,$udom);
7668: my $result= <<SCANTRONFORM;
7669: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7670: <input type="hidden" name="command" value="scantron_configphase" />
7671: $default_form_data
7672: SCANTRONFORM
7673: $r->print($result);
7674:
7675: my @delayqueue;
7676: my (%completedstudents,%scandata);
7677:
7678: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
7679: my $count=&get_todo_count($scanlines,$scan_data);
7680: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
7681: 'Bubblesheet Progress',$count,
7682: 'inline',undef,'scantronupload');
7683: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
7684: 'Processing first student');
7685: $r->print('<br />');
7686: my $start=&Time::HiRes::time();
7687: my $i=-1;
7688: my $started;
7689:
7690: my $nav_error;
7691: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
7692: if ($nav_error) {
7693: $r->print(&navmap_errormsg());
7694: return '';
7695: }
7696:
7697: # If an ssi failed in scantron_get_maxbubble, put an error message out to
7698: # the user and return.
7699:
7700: if ($ssi_error) {
7701: $r->print("</form>");
7702: &ssi_print_error($r);
7703: &Apache::lonnet::remove_lock($lock);
7704: return ''; # Dunno why the other returns return '' rather than just returning.
7705: }
7706:
7707: my %lettdig = &letter_to_digits();
7708: my $numletts = scalar(keys(%lettdig));
7709:
7710: while ($i<$scanlines->{'count'}) {
7711: ($uname,$udom)=('','');
7712: $i++;
7713: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7714: if ($line=~/^[\s\cz]*$/) { next; }
7715: if ($started) {
7716: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
7717: 'last student');
7718: }
7719: $started=1;
7720: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7721: $scan_data);
7722: unless ($uname=&scantron_find_student($scan_record,$scan_data,
7723: \%idmap,$i)) {
7724: &scantron_add_delay(\@delayqueue,$line,
7725: 'Unable to find a student that matches',1);
7726: next;
7727: }
7728: if (exists $completedstudents{$uname}) {
7729: &scantron_add_delay(\@delayqueue,$line,
7730: 'Student '.$uname.' has multiple sheets',2);
7731: next;
7732: }
7733: ($uname,$udom)=split(/:/,$uname);
7734:
7735: my (%partids_by_symb,$res_error);
7736: foreach my $resource (@resources) {
7737: my $ressymb;
7738: if (ref($resource)) {
7739: $ressymb = $resource->symb();
7740: } else {
7741: $res_error = 1;
7742: last;
7743: }
7744: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
7745: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
7746: my ($analysis,$parts) =
7747: &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
7748: $partids_by_symb{$ressymb} = $parts;
7749: } else {
7750: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
7751: }
7752: }
7753:
7754: if ($res_error) {
7755: &scantron_add_delay(\@delayqueue,$line,
7756: 'An error occurred while grading student '.$uname,2);
7757: next;
7758: }
7759:
7760: &Apache::lonxml::clear_problem_counter();
7761: &Apache::lonnet::appenv($scan_record);
7762:
7763: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
7764: &scantron_putfile($scanlines,$scan_data);
7765: }
7766:
7767: my $scancode;
7768: if ((exists($scan_record->{'scantron.CODE'})) &&
7769: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
7770: $scancode = $scan_record->{'scantron.CODE'};
7771: } else {
7772: $scancode = '';
7773: }
7774:
7775: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7776: \@resources,\%partids_by_symb,
7777: $bubbles_per_row) eq 'ssi_error') {
7778: $ssi_error = 0; # So end of handler error message does not trigger.
7779: $r->print("</form>");
7780: &ssi_print_error($r);
7781: &Apache::lonnet::remove_lock($lock);
7782: return ''; # Why return ''? Beats me.
7783: }
7784:
7785: $completedstudents{$uname}={'line'=>$line};
7786: if ($env{'form.verifyrecord'}) {
7787: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
7788: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
7789: chomp($studentdata);
7790: $studentdata =~ s/\r$//;
7791: my $studentrecord = '';
7792: my $counter = -1;
7793: foreach my $resource (@resources) {
7794: my $ressymb = $resource->symb();
7795: ($counter,my $recording) =
7796: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7797: $counter,$studentdata,$partids_by_symb{$ressymb},
7798: \%scantron_config,\%lettdig,$numletts);
7799: $studentrecord .= $recording;
7800: }
7801: if ($studentrecord ne $studentdata) {
7802: &Apache::lonxml::clear_problem_counter();
7803: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7804: \@resources,\%partids_by_symb,
7805: $bubbles_per_row) eq 'ssi_error') {
7806: $ssi_error = 0; # So end of handler error message does not trigger.
7807: $r->print("</form>");
7808: &ssi_print_error($r);
7809: &Apache::lonnet::remove_lock($lock);
7810: delete($completedstudents{$uname});
7811: return '';
7812: }
7813: $counter = -1;
7814: $studentrecord = '';
7815: foreach my $resource (@resources) {
7816: my $ressymb = $resource->symb();
7817: ($counter,my $recording) =
7818: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7819: $counter,$studentdata,$partids_by_symb{$ressymb},
7820: \%scantron_config,\%lettdig,$numletts);
7821: $studentrecord .= $recording;
7822: }
7823: if ($studentrecord ne $studentdata) {
7824: $r->print('<p><span class="LC_error">');
7825: if ($scancode eq '') {
7826: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
7827: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
7828: } else {
7829: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
7830: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
7831: }
7832: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
7833: &Apache::loncommon::start_data_table_header_row()."\n".
7834: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
7835: &Apache::loncommon::end_data_table_header_row()."\n".
7836: &Apache::loncommon::start_data_table_row().
7837: '<td>'.&mt('Bubble Sheet').'</td>'.
7838: '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
7839: &Apache::loncommon::end_data_table_row().
7840: &Apache::loncommon::start_data_table_row().
7841: '<td>Stored submissions</td>'.
7842: '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
7843: &Apache::loncommon::end_data_table_row().
7844: &Apache::loncommon::end_data_table().'</p>');
7845: } else {
7846: $r->print('<br /><span class="LC_warning">'.
7847: &mt('A second grading pass was needed for user: [_1] with ID: [_2], because a mismatch was seen on the first pass.',$uname.':'.$udom,$scan_record->{'scantron.ID'}).'<br />'.
7848: &mt("As a consequence, this user's submission history records two tries.").
7849: '</span><br />');
7850: }
7851: }
7852: }
7853: if (&Apache::loncommon::connection_aborted($r)) { last; }
7854: } continue {
7855: &Apache::lonxml::clear_problem_counter();
7856: &Apache::lonnet::delenv('scantron.');
7857: }
7858: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7859: &Apache::lonnet::remove_lock($lock);
7860: # my $lasttime = &Time::HiRes::time()-$start;
7861: # $r->print("<p>took $lasttime</p>");
7862:
7863: $r->print("</form>");
7864: return '';
7865: }
7866:
7867: sub graders_resources_pass {
7868: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
7869: $bubbles_per_row) = @_;
7870: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
7871: (ref($grader_randomlists_by_symb) eq 'HASH')) {
7872: foreach my $resource (@{$resources}) {
7873: my $ressymb = $resource->symb();
7874: my ($analysis,$parts) =
7875: &scantron_partids_tograde($resource,$env{'request.course.id'},
7876: $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
7877: $grader_partids_by_symb->{$ressymb} = $parts;
7878: if (ref($analysis) eq 'HASH') {
7879: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7880: $grader_randomlists_by_symb->{$ressymb} =
7881: $analysis->{'parts_withrandomlist'};
7882: }
7883: }
7884: }
7885: }
7886: return;
7887: }
7888:
7889: sub grade_student_bubbles {
7890: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
7891: # Walk folder as student here to get resources in order student sees.
7892: if (ref($resources) eq 'ARRAY') {
7893: my $count = 0;
7894: foreach my $resource (@{$resources}) {
7895: my $ressymb = $resource->symb();
7896: my %form = ('submitted' => 'scantron',
7897: 'grade_target' => 'grade',
7898: 'grade_username' => $uname,
7899: 'grade_domain' => $udom,
7900: 'grade_courseid' => $env{'request.course.id'},
7901: 'grade_symb' => $ressymb,
7902: 'CODE' => $scancode
7903: );
7904: if ($bubbles_per_row ne '') {
7905: $form{'bubbles_per_row'} = $bubbles_per_row;
7906: }
7907: if (ref($parts) eq 'HASH') {
7908: if (ref($parts->{$ressymb}) eq 'ARRAY') {
7909: foreach my $part (@{$parts->{$ressymb}}) {
7910: $form{'scantron_questnum_start.'.$part} =
7911: 1+$env{'form.scantron.first_bubble_line.'.$count};
7912: $count++;
7913: }
7914: }
7915: }
7916: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
7917: return 'ssi_error' if ($ssi_error);
7918: last if (&Apache::loncommon::connection_aborted($r));
7919: }
7920: }
7921: return;
7922: }
7923:
7924: sub scantron_upload_scantron_data {
7925: my ($r,$symb)=@_;
7926: my $dom = $env{'request.role.domain'};
7927: my $domdesc = &Apache::lonnet::domain($dom,'description');
7928: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
7929: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7930: 'domainid',
7931: 'coursename',$dom);
7932: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
7933: (' 'x2).&mt('(shows course personnel)');
7934: my $default_form_data=&defaultFormData($symb);
7935: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
7936: my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
7937: $r->print(&Apache::lonhtmlcommon::scripttag('
7938: function checkUpload(formname) {
7939: if (formname.upfile.value == "") {
7940: alert("'.$nofile_alert.'");
7941: return false;
7942: }
7943: if (formname.courseid.value == "") {
7944: alert("'.$nocourseid_alert.'");
7945: return false;
7946: }
7947: formname.submit();
7948: }
7949:
7950: function ToSyllabus() {
7951: var cdom = '."'$dom'".';
7952: var cnum = document.rules.courseid.value;
7953: if (cdom == "" || cdom == null) {
7954: return;
7955: }
7956: if (cnum == "" || cnum == null) {
7957: return;
7958: }
7959: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
7960: "height=350,width=350,scrollbars=yes,menubar=no");
7961: return;
7962: }
7963:
7964: '));
7965: $r->print('
7966: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
7967:
7968: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
7969: '.$default_form_data.
7970: &Apache::lonhtmlcommon::start_pick_box().
7971: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
7972: '<input name="courseid" type="text" size="30" />'.$select_link.
7973: &Apache::lonhtmlcommon::row_closure().
7974: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
7975: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
7976: &Apache::lonhtmlcommon::row_closure().
7977: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
7978: '<input name="domainid" type="hidden" />'.$domdesc.
7979: &Apache::lonhtmlcommon::row_closure().
7980: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
7981: '<input type="file" name="upfile" size="50" />'.
7982: &Apache::lonhtmlcommon::row_closure(1).
7983: &Apache::lonhtmlcommon::end_pick_box().'<br />
7984:
7985: <input name="command" value="scantronupload_save" type="hidden" />
7986: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
7987: </form>
7988: ');
7989: return '';
7990: }
7991:
7992:
7993: sub scantron_upload_scantron_data_save {
7994: my($r,$symb)=@_;
7995: my $doanotherupload=
7996: '<br /><form action="/adm/grades" method="post">'."\n".
7997: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7998: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
7999: '</form>'."\n";
8000: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
8001: !&Apache::lonnet::allowed('usc',
8002: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
8003: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
8004: unless ($symb) {
8005: $r->print($doanotherupload);
8006: }
8007: return '';
8008: }
8009: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
8010: my $uploadedfile;
8011: $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
8012: if (length($env{'form.upfile'}) < 2) {
8013: $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8014: } else {
8015: my $result =
8016: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
8017: $env{'form.courseid'},$env{'form.domainid'});
8018: if ($result =~ m{^/uploaded/}) {
8019: $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
8020: '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
8021: '<span class="LC_filename">'.$result.'</span>'));
8022: ($uploadedfile) = ($result =~ m{/([^/]+)$});
8023: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
8024: $env{'form.courseid'},$uploadedfile));
8025: } else {
8026: $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
8027: '<span class="LC_error">','</span>',$result,
8028: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8029: }
8030: }
8031: if ($symb) {
8032: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
8033: } else {
8034: $r->print($doanotherupload);
8035: }
8036: return '';
8037: }
8038:
8039: sub validate_uploaded_scantron_file {
8040: my ($cdom,$cname,$fname) = @_;
8041: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
8042: my @lines;
8043: if ($scanlines ne '-1') {
8044: @lines=split("\n",$scanlines,-1);
8045: }
8046: my $output;
8047: if (@lines) {
8048: my (%counts,$max_match_format);
8049: my ($max_match_count,$max_match_pct) = (0,0);
8050: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
8051: my %idmap = &username_to_idmap($classlist);
8052: foreach my $key (keys(%idmap)) {
8053: my $lckey = lc($key);
8054: $idmap{$lckey} = $idmap{$key};
8055: }
8056: my %unique_formats;
8057: my @formatlines = &get_scantronformat_file();
8058: foreach my $line (@formatlines) {
8059: chomp($line);
8060: my @config = split(/:/,$line);
8061: my $idstart = $config[5];
8062: my $idlength = $config[6];
8063: if (($idstart ne '') && ($idlength > 0)) {
8064: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
8065: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
8066: } else {
8067: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
8068: }
8069: }
8070: }
8071: foreach my $key (keys(%unique_formats)) {
8072: my ($idstart,$idlength) = split(':',$key);
8073: %{$counts{$key}} = (
8074: 'found' => 0,
8075: 'total' => 0,
8076: );
8077: foreach my $line (@lines) {
8078: next if ($line =~ /^#/);
8079: next if ($line =~ /^[\s\cz]*$/);
8080: my $id = substr($line,$idstart-1,$idlength);
8081: $id = lc($id);
8082: if (exists($idmap{$id})) {
8083: $counts{$key}{'found'} ++;
8084: }
8085: $counts{$key}{'total'} ++;
8086: }
8087: if ($counts{$key}{'total'}) {
8088: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
8089: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
8090: $max_match_pct = $percent_match;
8091: $max_match_format = $key;
8092: $max_match_count = $counts{$key}{'total'};
8093: }
8094: }
8095: }
8096: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
8097: my $format_descs;
8098: my $numwithformat = @{$unique_formats{$max_match_format}};
8099: for (my $i=0; $i<$numwithformat; $i++) {
8100: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8101: if ($i<$numwithformat-2) {
8102: $format_descs .= '"<i>'.$desc.'</i>", ';
8103: } elsif ($i==$numwithformat-2) {
8104: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8105: } elsif ($i==$numwithformat-1) {
8106: $format_descs .= '"<i>'.$desc.'</i>"';
8107: }
8108: }
8109: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8110: $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
8111: '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
8112: '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
8113: '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
8114: '<i>'.$cdom.'</i>').'</li>'.
8115: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8116: '<li>'.&mt('The course roster is not up to date').'</li>'.
8117: '</ul>';
8118: }
8119: } else {
8120: $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
8121: }
8122: return $output;
8123: }
8124:
8125: sub valid_file {
8126: my ($requested_file)=@_;
8127: foreach my $filename (sort(&scantron_filenames())) {
8128: if ($requested_file eq $filename) { return 1; }
8129: }
8130: return 0;
8131: }
8132:
8133: sub scantron_download_scantron_data {
8134: my ($r,$symb)=@_;
8135: my $default_form_data=&defaultFormData($symb);
8136: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8137: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8138: my $file=$env{'form.scantron_selectfile'};
8139: if (! &valid_file($file)) {
8140: $r->print('
8141: <p>
8142: '.&mt('The requested file name was invalid.').'
8143: </p>
8144: ');
8145: return;
8146: }
8147: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8148: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8149: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8150: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8151: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8152: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8153: $r->print('
8154: <p>
8155: '.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
8156: '<a href="'.$orig.'">','</a>').'
8157: </p>
8158: <p>
8159: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8160: '<a href="'.$corrected.'">','</a>').'
8161: </p>
8162: <p>
8163: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
8164: '<a href="'.$skipped.'">','</a>').'
8165: </p>
8166: ');
8167: return '';
8168: }
8169:
8170: sub checkscantron_results {
8171: my ($r,$symb) = @_;
8172: if (!$symb) {return '';}
8173: my $cid = $env{'request.course.id'};
8174: my %lettdig = &letter_to_digits();
8175: my $numletts = scalar(keys(%lettdig));
8176: my $cnum = $env{'course.'.$cid.'.num'};
8177: my $cdom = $env{'course.'.$cid.'.domain'};
8178: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
8179: my %record;
8180: my %scantron_config =
8181: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
8182: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8183: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
8184: my $classlist=&Apache::loncoursedata::get_classlist();
8185: my %idmap=&Apache::grades::username_to_idmap($classlist);
8186: my $navmap=Apache::lonnavmaps::navmap->new();
8187: unless (ref($navmap)) {
8188: $r->print(&navmap_errormsg());
8189: return '';
8190: }
8191: my $map=$navmap->getResourceByUrl($sequence);
8192: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8193: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
8194: &graders_resources_pass(\@resources,\%grader_partids_by_symb, \%grader_randomlists_by_symb);
8195:
8196: my ($uname,$udom);
8197: my (%scandata,%lastname,%bylast);
8198: $r->print('
8199: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
8200:
8201: my @delayqueue;
8202: my %completedstudents;
8203:
8204: my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
8205: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
8206: 'Progress of Bubblesheet Data/Submission Records Comparison',$count,
8207: 'inline',undef,'checkscantron');
8208: my ($username,$domain,$started);
8209: my $nav_error;
8210: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8211: if ($nav_error) {
8212: $r->print(&navmap_errormsg());
8213: return '';
8214: }
8215:
8216: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
8217: 'Processing first student');
8218: my $start=&Time::HiRes::time();
8219: my $i=-1;
8220:
8221: while ($i<$scanlines->{'count'}) {
8222: ($username,$domain,$uname)=('','','');
8223: $i++;
8224: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
8225: if ($line=~/^[\s\cz]*$/) { next; }
8226: if ($started) {
8227: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
8228: 'last student');
8229: }
8230: $started=1;
8231: my $scan_record=
8232: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
8233: $scan_data);
8234: unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
8235: \%idmap,$i)) {
8236: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8237: 'Unable to find a student that matches',1);
8238: next;
8239: }
8240: if (exists $completedstudents{$uname}) {
8241: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8242: 'Student '.$uname.' has multiple sheets',2);
8243: next;
8244: }
8245: my $pid = $scan_record->{'scantron.ID'};
8246: $lastname{$pid} = $scan_record->{'scantron.LastName'};
8247: push(@{$bylast{$lastname{$pid}}},$pid);
8248: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8249: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8250: chomp($scandata{$pid});
8251: $scandata{$pid} =~ s/\r$//;
8252: ($username,$domain)=split(/:/,$uname);
8253: my $counter = -1;
8254: foreach my $resource (@resources) {
8255: my $parts;
8256: my $ressymb = $resource->symb();
8257: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8258: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8259: (my $analysis,$parts) =
8260: &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
8261: } else {
8262: $parts = $grader_partids_by_symb{$ressymb};
8263: }
8264: ($counter,my $recording) =
8265: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
8266: $scandata{$pid},$parts,
8267: \%scantron_config,\%lettdig,$numletts);
8268: $record{$pid} .= $recording;
8269: }
8270: }
8271: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8272: $r->print('<br />');
8273: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
8274: $passed = 0;
8275: $failed = 0;
8276: $numstudents = 0;
8277: foreach my $last (sort(keys(%bylast))) {
8278: if (ref($bylast{$last}) eq 'ARRAY') {
8279: foreach my $pid (sort(@{$bylast{$last}})) {
8280: my $showscandata = $scandata{$pid};
8281: my $showrecord = $record{$pid};
8282: $showscandata =~ s/\s/ /g;
8283: $showrecord =~ s/\s/ /g;
8284: if ($scandata{$pid} eq $record{$pid}) {
8285: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
8286: $okstudents .= '<tr class="'.$css_class.'">'.
8287: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8288: '</tr>'."\n".
8289: '<tr class="'.$css_class.'">'."\n".
8290: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
8291: $passed ++;
8292: } else {
8293: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
8294: $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Bubblesheet').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8295: '</tr>'."\n".
8296: '<tr class="'.$css_class.'">'."\n".
8297: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
8298: '</tr>'."\n";
8299: $failed ++;
8300: }
8301: $numstudents ++;
8302: }
8303: }
8304: }
8305: $r->print(
8306: '<p>'
8307: .&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
8308: '<b>',
8309: $numstudents,
8310: '</b>',
8311: $env{'form.scantron_maxbubble'})
8312: .'</p>'
8313: );
8314: $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>');
8315: if ($passed) {
8316: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
8317: $r->print(&Apache::loncommon::start_data_table()."\n".
8318: &Apache::loncommon::start_data_table_header_row()."\n".
8319: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8320: &Apache::loncommon::end_data_table_header_row()."\n".
8321: $okstudents."\n".
8322: &Apache::loncommon::end_data_table().'<br />');
8323: }
8324: if ($failed) {
8325: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
8326: $r->print(&Apache::loncommon::start_data_table()."\n".
8327: &Apache::loncommon::start_data_table_header_row()."\n".
8328: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8329: &Apache::loncommon::end_data_table_header_row()."\n".
8330: $badstudents."\n".
8331: &Apache::loncommon::end_data_table()).'<br />'.
8332: &mt('Differences can occur if submissions were modified using manual grading after a bubblesheet grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original bubblesheets.');
8333: }
8334: $r->print('</form><br />');
8335: return;
8336: }
8337:
8338: sub verify_scantron_grading {
8339: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
8340: $scantron_config,$lettdig,$numletts) = @_;
8341: my ($record,%expected,%startpos);
8342: return ($counter,$record) if (!ref($resource));
8343: return ($counter,$record) if (!$resource->is_problem());
8344: my $symb = $resource->symb();
8345: return ($counter,$record) if (ref($partids) ne 'ARRAY');
8346: foreach my $part_id (@{$partids}) {
8347: $counter ++;
8348: $expected{$part_id} = 0;
8349: if ($env{"form.scantron.sub_bubblelines.$counter"}) {
8350: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
8351: foreach my $item (@sub_lines) {
8352: $expected{$part_id} += $item;
8353: }
8354: } else {
8355: $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
8356: }
8357: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
8358: }
8359: if ($symb) {
8360: my %recorded;
8361: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
8362: if ($returnhash{'version'}) {
8363: my %lasthash=();
8364: my $version;
8365: for ($version=1;$version<=$returnhash{'version'};$version++) {
8366: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
8367: $lasthash{$key}=$returnhash{$version.':'.$key};
8368: }
8369: }
8370: foreach my $key (keys(%lasthash)) {
8371: if ($key =~ /\.scantron$/) {
8372: my $value = &unescape($lasthash{$key});
8373: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
8374: if ($value eq '') {
8375: for (my $i=0; $i<$expected{$part_id}; $i++) {
8376: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
8377: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8378: }
8379: }
8380: } else {
8381: my @tocheck;
8382: my @items = split(//,$value);
8383: if (($scantron_config->{'Qon'} eq 'letter') ||
8384: ($scantron_config->{'Qon'} eq 'number')) {
8385: if (@items < $expected{$part_id}) {
8386: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
8387: my @singles = split(//,$fragment);
8388: foreach my $pos (@singles) {
8389: if ($pos eq ' ') {
8390: push(@tocheck,$pos);
8391: } else {
8392: my $next = shift(@items);
8393: push(@tocheck,$next);
8394: }
8395: }
8396: } else {
8397: @tocheck = @items;
8398: }
8399: foreach my $letter (@tocheck) {
8400: if ($scantron_config->{'Qon'} eq 'letter') {
8401: if ($letter !~ /^[A-J]$/) {
8402: $letter = $scantron_config->{'Qoff'};
8403: }
8404: $recorded{$part_id} .= $letter;
8405: } elsif ($scantron_config->{'Qon'} eq 'number') {
8406: my $digit;
8407: if ($letter !~ /^[A-J]$/) {
8408: $digit = $scantron_config->{'Qoff'};
8409: } else {
8410: $digit = $lettdig->{$letter};
8411: }
8412: $recorded{$part_id} .= $digit;
8413: }
8414: }
8415: } else {
8416: @tocheck = @items;
8417: for (my $i=0; $i<$expected{$part_id}; $i++) {
8418: my $curr_sub = shift(@tocheck);
8419: my $digit;
8420: if ($curr_sub =~ /^[A-J]$/) {
8421: $digit = $lettdig->{$curr_sub}-1;
8422: }
8423: if ($curr_sub eq 'J') {
8424: $digit += scalar($numletts);
8425: }
8426: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8427: if ($j == $digit) {
8428: $recorded{$part_id} .= $scantron_config->{'Qon'};
8429: } else {
8430: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8431: }
8432: }
8433: }
8434: }
8435: }
8436: }
8437: }
8438: }
8439: foreach my $part_id (@{$partids}) {
8440: if ($recorded{$part_id} eq '') {
8441: for (my $i=0; $i<$expected{$part_id}; $i++) {
8442: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8443: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8444: }
8445: }
8446: }
8447: $record .= $recorded{$part_id};
8448: }
8449: }
8450: return ($counter,$record);
8451: }
8452:
8453: sub letter_to_digits {
8454: my %lettdig = (
8455: A => 1,
8456: B => 2,
8457: C => 3,
8458: D => 4,
8459: E => 5,
8460: F => 6,
8461: G => 7,
8462: H => 8,
8463: I => 9,
8464: J => 0,
8465: );
8466: return %lettdig;
8467: }
8468:
8469:
8470: #-------- end of section for handling grading scantron forms -------
8471: #
8472: #-------------------------------------------------------------------
8473:
8474: #-------------------------- Menu interface -------------------------
8475: #
8476: #--- Href with symb and command ---
8477:
8478: sub href_symb_cmd {
8479: my ($symb,$cmd)=@_;
8480: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
8481: }
8482:
8483: sub grading_menu {
8484: my ($request,$symb) = @_;
8485: if (!$symb) {return '';}
8486:
8487: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
8488: 'command'=>'individual');
8489:
8490: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8491:
8492: $fields{'command'}='ungraded';
8493: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8494:
8495: $fields{'command'}='table';
8496: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8497:
8498: $fields{'command'}='all_for_one';
8499: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8500:
8501: $fields{'command'}='downloadfilesselect';
8502: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8503:
8504: $fields{'command'} = 'csvform';
8505: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8506:
8507: $fields{'command'} = 'processclicker';
8508: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8509:
8510: $fields{'command'} = 'scantron_selectphase';
8511: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8512:
8513: $fields{'command'} = 'initialverifyreceipt';
8514: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8515:
8516: my @menu = ({ categorytitle=>'Hand Grading',
8517: items =>[
8518: { linktext => 'Select individual students to grade',
8519: url => $url1a,
8520: permission => 'F',
8521: icon => 'grade_students.png',
8522: linktitle => 'Grade current resource for a selection of students.'
8523: },
8524: { linktext => 'Grade ungraded submissions.',
8525: url => $url1b,
8526: permission => 'F',
8527: icon => 'ungrade_sub.png',
8528: linktitle => 'Grade all submissions that have not been graded yet.'
8529: },
8530:
8531: { linktext => 'Grading table',
8532: url => $url1c,
8533: permission => 'F',
8534: icon => 'grading_table.png',
8535: linktitle => 'Grade current resource for all students.'
8536: },
8537: { linktext => 'Grade page/folder for one student',
8538: url => $url1d,
8539: permission => 'F',
8540: icon => 'grade_PageFolder.png',
8541: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
8542: },
8543: { linktext => 'Download submissions',
8544: url => $url1e,
8545: permission => 'F',
8546: icon => 'download_sub.png',
8547: linktitle => 'Download all students submissions.'
8548: }]},
8549: { categorytitle=>'Automated Grading',
8550: items =>[
8551:
8552: { linktext => 'Upload Scores',
8553: url => $url2,
8554: permission => 'F',
8555: icon => 'uploadscores.png',
8556: linktitle => 'Specify a file containing the class scores for current resource.'
8557: },
8558: { linktext => 'Process Clicker',
8559: url => $url3,
8560: permission => 'F',
8561: icon => 'addClickerInfoFile.png',
8562: linktitle => 'Specify a file containing the clicker information for this resource.'
8563: },
8564: { linktext => 'Grade/Manage/Review Bubblesheets',
8565: url => $url4,
8566: permission => 'F',
8567: icon => 'bubblesheet.png',
8568: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
8569: },
8570: { linktext => 'Verify Receipt Number',
8571: url => $url5,
8572: permission => 'F',
8573: icon => 'receipt_number.png',
8574: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
8575: }
8576:
8577: ]
8578: });
8579:
8580: # Create the menu
8581: my $Str;
8582: $Str .= '<form method="post" action="" name="gradingMenu">';
8583: $Str .= '<input type="hidden" name="command" value="" />'.
8584: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8585:
8586: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
8587: return $Str;
8588: }
8589:
8590:
8591: sub ungraded {
8592: my ($request)=@_;
8593: &submit_options($request);
8594: }
8595:
8596: sub submit_options_sequence {
8597: my ($request,$symb) = @_;
8598: if (!$symb) {return '';}
8599: &commonJSfunctions($request);
8600: my $result;
8601:
8602: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8603: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8604: $result.=&selectfield(0).
8605: '<input type="hidden" name="command" value="pickStudentPage" />
8606: <div>
8607: <input type="submit" value="'.&mt('Next').' →" />
8608: </div>
8609: </div>
8610: </form>';
8611: return $result;
8612: }
8613:
8614: sub submit_options_table {
8615: my ($request,$symb) = @_;
8616: if (!$symb) {return '';}
8617: &commonJSfunctions($request);
8618: my $result;
8619:
8620: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8621: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8622:
8623: $result.=&selectfield(0).
8624: '<input type="hidden" name="command" value="viewgrades" />
8625: <div>
8626: <input type="submit" value="'.&mt('Next').' →" />
8627: </div>
8628: </div>
8629: </form>';
8630: return $result;
8631: }
8632:
8633: sub submit_options_download {
8634: my ($request,$symb) = @_;
8635: if (!$symb) {return '';}
8636:
8637: &commonJSfunctions($request);
8638:
8639: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8640: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8641: $result.='
8642: <h2>
8643: '.&mt('Select Students for Which to Download Submissions').'
8644: </h2>'.&selectfield(1).'
8645: <input type="hidden" name="command" value="downloadfileslink" />
8646: <input type="submit" value="'.&mt('Next').' →" />
8647: </div>
8648: </div>
8649:
8650:
8651: </form>';
8652: return $result;
8653: }
8654:
8655: #--- Displays the submissions first page -------
8656: sub submit_options {
8657: my ($request,$symb) = @_;
8658: if (!$symb) {return '';}
8659:
8660: &commonJSfunctions($request);
8661: my $result;
8662:
8663: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8664: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8665: $result.=&selectfield(1).'
8666: <input type="hidden" name="command" value="submission" />
8667: <input type="submit" value="'.&mt('Next').' →" />
8668: </div>
8669: </div>
8670:
8671:
8672: </form>';
8673: return $result;
8674: }
8675:
8676: sub selectfield {
8677: my ($full)=@_;
8678: my %options =
8679: (&Apache::lonlocal::texthash(
8680: 'yes' => 'with submissions',
8681: 'queued' => 'in grading queue',
8682: 'graded' => 'with ungraded submissions',
8683: 'incorrect' => 'with incorrect submissions',
8684: 'all' => 'with any status'),
8685: 'select_form_order' => ['yes','queued','graded','incorrect','all']);
8686: my $result='<div class="LC_columnSection">
8687:
8688: <fieldset>
8689: <legend>
8690: '.&mt('Sections').'
8691: </legend>
8692: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
8693: </fieldset>
8694:
8695: <fieldset>
8696: <legend>
8697: '.&mt('Groups').'
8698: </legend>
8699: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
8700: </fieldset>
8701:
8702: <fieldset>
8703: <legend>
8704: '.&mt('Access Status').'
8705: </legend>
8706: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
8707: </fieldset>';
8708: if ($full) {
8709: $result.='
8710: <fieldset>
8711: <legend>
8712: '.&mt('Submission Status').'
8713: </legend>'.
8714: &Apache::loncommon::select_form('all','submitonly',\%options).
8715: '</fieldset>';
8716: }
8717: $result.='</div><br />';
8718: return $result;
8719: }
8720:
8721: sub reset_perm {
8722: undef(%perm);
8723: }
8724:
8725: sub init_perm {
8726: &reset_perm();
8727: foreach my $test_perm ('vgr','mgr','opa') {
8728:
8729: my $scope = $env{'request.course.id'};
8730: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
8731:
8732: $scope .= '/'.$env{'request.course.sec'};
8733: if ( $perm{$test_perm}=
8734: &Apache::lonnet::allowed($test_perm,$scope)) {
8735: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
8736: } else {
8737: delete($perm{$test_perm});
8738: }
8739: }
8740: }
8741: }
8742:
8743: sub gather_clicker_ids {
8744: my %clicker_ids;
8745:
8746: my $classlist = &Apache::loncoursedata::get_classlist();
8747:
8748: # Set up a couple variables.
8749: my $username_idx = &Apache::loncoursedata::CL_SNAME();
8750: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
8751: my $status_idx = &Apache::loncoursedata::CL_STATUS();
8752:
8753: foreach my $student (keys(%$classlist)) {
8754: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
8755: my $username = $classlist->{$student}->[$username_idx];
8756: my $domain = $classlist->{$student}->[$domain_idx];
8757: my $clickers =
8758: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
8759: foreach my $id (split(/\,/,$clickers)) {
8760: $id=~s/^[\#0]+//;
8761: $id=~s/[\-\:]//g;
8762: if (exists($clicker_ids{$id})) {
8763: $clicker_ids{$id}.=','.$username.':'.$domain;
8764: } else {
8765: $clicker_ids{$id}=$username.':'.$domain;
8766: }
8767: }
8768: }
8769: return %clicker_ids;
8770: }
8771:
8772: sub gather_adv_clicker_ids {
8773: my %clicker_ids;
8774: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
8775: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8776: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
8777: foreach my $element (sort(keys(%coursepersonnel))) {
8778: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
8779: my ($puname,$pudom)=split(/\:/,$person);
8780: my $clickers =
8781: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
8782: foreach my $id (split(/\,/,$clickers)) {
8783: $id=~s/^[\#0]+//;
8784: $id=~s/[\-\:]//g;
8785: if (exists($clicker_ids{$id})) {
8786: $clicker_ids{$id}.=','.$puname.':'.$pudom;
8787: } else {
8788: $clicker_ids{$id}=$puname.':'.$pudom;
8789: }
8790: }
8791: }
8792: }
8793: return %clicker_ids;
8794: }
8795:
8796: sub clicker_grading_parameters {
8797: return ('gradingmechanism' => 'scalar',
8798: 'upfiletype' => 'scalar',
8799: 'specificid' => 'scalar',
8800: 'pcorrect' => 'scalar',
8801: 'pincorrect' => 'scalar');
8802: }
8803:
8804: sub process_clicker {
8805: my ($r,$symb)=@_;
8806: if (!$symb) {return '';}
8807: my $result=&checkforfile_js();
8808: $result.=&Apache::loncommon::start_data_table().
8809: &Apache::loncommon::start_data_table_header_row().
8810: '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
8811: &Apache::loncommon::end_data_table_header_row().
8812: &Apache::loncommon::start_data_table_row()."<td>\n";
8813: # Attempt to restore parameters from last session, set defaults if not present
8814: my %Saveable_Parameters=&clicker_grading_parameters();
8815: &Apache::loncommon::restore_course_settings('grades_clicker',
8816: \%Saveable_Parameters);
8817: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
8818: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
8819: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
8820: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
8821:
8822: my %checked;
8823: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
8824: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
8825: $checked{$gradingmechanism}=' checked="checked"';
8826: }
8827: }
8828:
8829: my $upload=&mt("Evaluate File");
8830: my $type=&mt("Type");
8831: my $attendance=&mt("Award points just for participation");
8832: my $personnel=&mt("Correctness determined from response by course personnel");
8833: my $specific=&mt("Correctness determined from response with clicker ID(s)");
8834: my $given=&mt("Correctness determined from given list of answers").' '.
8835: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
8836: my $pcorrect=&mt("Percentage points for correct solution");
8837: my $pincorrect=&mt("Percentage points for incorrect solution");
8838: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
8839: {'iclicker' => 'i>clicker',
8840: 'interwrite' => 'interwrite PRS'});
8841: $symb = &Apache::lonenc::check_encrypt($symb);
8842: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
8843: function sanitycheck() {
8844: // Accept only integer percentages
8845: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
8846: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
8847: // Find out grading choice
8848: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8849: if (document.forms.gradesupload.gradingmechanism[i].checked) {
8850: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
8851: }
8852: }
8853: // By default, new choice equals user selection
8854: newgradingchoice=gradingchoice;
8855: // Not good to give more points for false answers than correct ones
8856: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
8857: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
8858: }
8859: // If new choice is attendance only, and old choice was correctness-based, restore defaults
8860: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
8861: document.forms.gradesupload.pcorrect.value=100;
8862: document.forms.gradesupload.pincorrect.value=100;
8863: }
8864: // If the values are different, cannot be attendance only
8865: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
8866: (gradingchoice=='attendance')) {
8867: newgradingchoice='personnel';
8868: }
8869: // Change grading choice to new one
8870: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8871: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
8872: document.forms.gradesupload.gradingmechanism[i].checked=true;
8873: } else {
8874: document.forms.gradesupload.gradingmechanism[i].checked=false;
8875: }
8876: }
8877: // Remember the old state
8878: document.forms.gradesupload.waschecked.value=newgradingchoice;
8879: }
8880: ENDUPFORM
8881: $result.= <<ENDUPFORM;
8882: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
8883: <input type="hidden" name="symb" value="$symb" />
8884: <input type="hidden" name="command" value="processclickerfile" />
8885: <input type="file" name="upfile" size="50" />
8886: <br /><label>$type: $selectform</label>
8887: ENDUPFORM
8888: $result.='</td>'.&Apache::loncommon::end_data_table_row().
8889: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
8890: <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
8891: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
8892: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
8893: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
8894: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
8895: <br />
8896: <input type="text" name="givenanswer" size="50" />
8897: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
8898: ENDGRADINGFORM
8899: $result.='</td>'.&Apache::loncommon::end_data_table_row().
8900: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
8901: <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
8902: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
8903: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
8904: </form>'
8905: ENDPERCFORM
8906: $result.='</td>'.
8907: &Apache::loncommon::end_data_table_row().
8908: &Apache::loncommon::end_data_table();
8909: return $result;
8910: }
8911:
8912: sub process_clicker_file {
8913: my ($r,$symb)=@_;
8914: if (!$symb) {return '';}
8915:
8916: my %Saveable_Parameters=&clicker_grading_parameters();
8917: &Apache::loncommon::store_course_settings('grades_clicker',
8918: \%Saveable_Parameters);
8919: my $result='';
8920: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
8921: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
8922: return $result;
8923: }
8924: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
8925: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
8926: return $result;
8927: }
8928: my $foundgiven=0;
8929: if ($env{'form.gradingmechanism'} eq 'given') {
8930: $env{'form.givenanswer'}=~s/^\s*//gs;
8931: $env{'form.givenanswer'}=~s/\s*$//gs;
8932: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
8933: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
8934: my @answers=split(/\,/,$env{'form.givenanswer'});
8935: $foundgiven=$#answers+1;
8936: }
8937: my %clicker_ids=&gather_clicker_ids();
8938: my %correct_ids;
8939: if ($env{'form.gradingmechanism'} eq 'personnel') {
8940: %correct_ids=&gather_adv_clicker_ids();
8941: }
8942: if ($env{'form.gradingmechanism'} eq 'specific') {
8943: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
8944: $correct_id=~tr/a-z/A-Z/;
8945: $correct_id=~s/\s//gs;
8946: $correct_id=~s/^[\#0]+//;
8947: $correct_id=~s/[\-\:]//g;
8948: if ($correct_id) {
8949: $correct_ids{$correct_id}='specified';
8950: }
8951: }
8952: }
8953: if ($env{'form.gradingmechanism'} eq 'attendance') {
8954: $result.=&mt('Score based on attendance only');
8955: } elsif ($env{'form.gradingmechanism'} eq 'given') {
8956: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
8957: } else {
8958: my $number=0;
8959: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
8960: foreach my $id (sort(keys(%correct_ids))) {
8961: $result.='<br /><tt>'.$id.'</tt> - ';
8962: if ($correct_ids{$id} eq 'specified') {
8963: $result.=&mt('specified');
8964: } else {
8965: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
8966: $result.=&Apache::loncommon::plainname($uname,$udom);
8967: }
8968: $number++;
8969: }
8970: $result.="</p>\n";
8971: if ($number==0) {
8972: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
8973: return $result;
8974: }
8975: }
8976: if (length($env{'form.upfile'}) < 2) {
8977: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
8978: '<span class="LC_error">',
8979: '</span>',
8980: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
8981: return $result;
8982: }
8983:
8984: # Were able to get all the info needed, now analyze the file
8985:
8986: $result.=&Apache::loncommon::studentbrowser_javascript();
8987: $symb = &Apache::lonenc::check_encrypt($symb);
8988: $result.=&Apache::loncommon::start_data_table().
8989: &Apache::loncommon::start_data_table_header_row().
8990: '<th>'.&mt('Evaluate clicker file').'</th>'.
8991: &Apache::loncommon::end_data_table_header_row().
8992: &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
8993: <td>
8994: <form method="post" action="/adm/grades" name="clickeranalysis">
8995: <input type="hidden" name="symb" value="$symb" />
8996: <input type="hidden" name="command" value="assignclickergrades" />
8997: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
8998: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
8999: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
9000: ENDHEADER
9001: if ($env{'form.gradingmechanism'} eq 'given') {
9002: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
9003: }
9004: my %responses;
9005: my @questiontitles;
9006: my $errormsg='';
9007: my $number=0;
9008: if ($env{'form.upfiletype'} eq 'iclicker') {
9009: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
9010: }
9011: if ($env{'form.upfiletype'} eq 'interwrite') {
9012: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
9013: }
9014: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
9015: '<input type="hidden" name="number" value="'.$number.'" />'.
9016: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
9017: $env{'form.pcorrect'},$env{'form.pincorrect'}).
9018: '<br />';
9019: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
9020: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
9021: return $result;
9022: }
9023: # Remember Question Titles
9024: # FIXME: Possibly need delimiter other than ":"
9025: for (my $i=0;$i<$number;$i++) {
9026: $result.='<input type="hidden" name="question:'.$i.'" value="'.
9027: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
9028: }
9029: my $correct_count=0;
9030: my $student_count=0;
9031: my $unknown_count=0;
9032: # Match answers with usernames
9033: # FIXME: Possibly need delimiter other than ":"
9034: foreach my $id (keys(%responses)) {
9035: if ($correct_ids{$id}) {
9036: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
9037: $correct_count++;
9038: } elsif ($clicker_ids{$id}) {
9039: if ($clicker_ids{$id}=~/\,/) {
9040: # More than one user with the same clicker!
9041: $result.="</td>".&Apache::loncommon::end_data_table_row().
9042: &Apache::loncommon::start_data_table_row()."<td>".
9043: &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
9044: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9045: "<select name='multi".$id."'>";
9046: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
9047: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
9048: }
9049: $result.='</select>';
9050: $unknown_count++;
9051: } else {
9052: # Good: found one and only one user with the right clicker
9053: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
9054: $student_count++;
9055: }
9056: } else {
9057: $result.="</td>".&Apache::loncommon::end_data_table_row().
9058: &Apache::loncommon::start_data_table_row()."<td>".
9059: &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
9060: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9061: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
9062: "\n".&mt("Domain").": ".
9063: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
9064: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
9065: $unknown_count++;
9066: }
9067: }
9068: $result.='<hr />'.
9069: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
9070: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
9071: if ($correct_count==0) {
9072: $errormsg.="Found no correct answers answers for grading!";
9073: } elsif ($correct_count>1) {
9074: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
9075: }
9076: }
9077: if ($number<1) {
9078: $errormsg.="Found no questions.";
9079: }
9080: if ($errormsg) {
9081: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
9082: } else {
9083: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
9084: }
9085: $result.='</form></td>'.
9086: &Apache::loncommon::end_data_table_row().
9087: &Apache::loncommon::end_data_table();
9088: return $result;
9089: }
9090:
9091: sub iclicker_eval {
9092: my ($questiontitles,$responses)=@_;
9093: my $number=0;
9094: my $errormsg='';
9095: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9096: my %components=&Apache::loncommon::record_sep($line);
9097: my @entries=map {$components{$_}} (sort(keys(%components)));
9098: if ($entries[0] eq 'Question') {
9099: for (my $i=3;$i<$#entries;$i+=6) {
9100: $$questiontitles[$number]=$entries[$i];
9101: $number++;
9102: }
9103: }
9104: if ($entries[0]=~/^\#/) {
9105: my $id=$entries[0];
9106: my @idresponses;
9107: $id=~s/^[\#0]+//;
9108: for (my $i=0;$i<$number;$i++) {
9109: my $idx=3+$i*6;
9110: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
9111: push(@idresponses,$entries[$idx]);
9112: }
9113: $$responses{$id}=join(',',@idresponses);
9114: }
9115: }
9116: return ($errormsg,$number);
9117: }
9118:
9119: sub interwrite_eval {
9120: my ($questiontitles,$responses)=@_;
9121: my $number=0;
9122: my $errormsg='';
9123: my $skipline=1;
9124: my $questionnumber=0;
9125: my %idresponses=();
9126: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9127: my %components=&Apache::loncommon::record_sep($line);
9128: my @entries=map {$components{$_}} (sort(keys(%components)));
9129: if ($entries[1] eq 'Time') { $skipline=0; next; }
9130: if ($entries[1] eq 'Response') { $skipline=1; }
9131: next if $skipline;
9132: if ($entries[0]!=$questionnumber) {
9133: $questionnumber=$entries[0];
9134: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
9135: $number++;
9136: }
9137: my $id=$entries[4];
9138: $id=~s/^[\#0]+//;
9139: $id=~s/^v\d*\://i;
9140: $id=~s/[\-\:]//g;
9141: $idresponses{$id}[$number]=$entries[6];
9142: }
9143: foreach my $id (keys(%idresponses)) {
9144: $$responses{$id}=join(',',@{$idresponses{$id}});
9145: $$responses{$id}=~s/^\s*\,//;
9146: }
9147: return ($errormsg,$number);
9148: }
9149:
9150: sub assign_clicker_grades {
9151: my ($r,$symb)=@_;
9152: if (!$symb) {return '';}
9153: # See which part we are saving to
9154: my $res_error;
9155: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
9156: if ($res_error) {
9157: return &navmap_errormsg();
9158: }
9159: # FIXME: This should probably look for the first handgradeable part
9160: my $part=$$partlist[0];
9161: # Start screen output
9162: my $result=&Apache::loncommon::start_data_table().
9163: &Apache::loncommon::start_data_table_header_row().
9164: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
9165: &Apache::loncommon::end_data_table_header_row().
9166: &Apache::loncommon::start_data_table_row().'<td>';
9167: # Get correct result
9168: # FIXME: Possibly need delimiter other than ":"
9169: my @correct=();
9170: my $gradingmechanism=$env{'form.gradingmechanism'};
9171: my $number=$env{'form.number'};
9172: if ($gradingmechanism ne 'attendance') {
9173: foreach my $key (keys(%env)) {
9174: if ($key=~/^form\.correct\:/) {
9175: my @input=split(/\,/,$env{$key});
9176: for (my $i=0;$i<=$#input;$i++) {
9177: if (($correct[$i]) && ($input[$i]) &&
9178: ($correct[$i] ne $input[$i])) {
9179: $result.='<br /><span class="LC_warning">'.
9180: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
9181: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
9182: } elsif (($input[$i]) || ($input[$i] eq '0')) {
9183: $correct[$i]=$input[$i];
9184: }
9185: }
9186: }
9187: }
9188: for (my $i=0;$i<$number;$i++) {
9189: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
9190: $result.='<br /><span class="LC_error">'.
9191: &mt('No correct result given for question "[_1]"!',
9192: $env{'form.question:'.$i}).'</span>';
9193: }
9194: }
9195: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
9196: }
9197: # Start grading
9198: my $pcorrect=$env{'form.pcorrect'};
9199: my $pincorrect=$env{'form.pincorrect'};
9200: my $storecount=0;
9201: my %users=();
9202: foreach my $key (keys(%env)) {
9203: my $user='';
9204: if ($key=~/^form\.student\:(.*)$/) {
9205: $user=$1;
9206: }
9207: if ($key=~/^form\.unknown\:(.*)$/) {
9208: my $id=$1;
9209: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
9210: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
9211: } elsif ($env{'form.multi'.$id}) {
9212: $user=$env{'form.multi'.$id};
9213: }
9214: }
9215: if ($user) {
9216: if ($users{$user}) {
9217: $result.='<br /><span class="LC_warning">'.
9218: &mt("More than one entry found for <tt>[_1]</tt>!",$user).
9219: '</span><br />';
9220: }
9221: $users{$user}=1;
9222: my @answer=split(/\,/,$env{$key});
9223: my $sum=0;
9224: my $realnumber=$number;
9225: for (my $i=0;$i<$number;$i++) {
9226: if ($correct[$i] eq '-') {
9227: $realnumber--;
9228: } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
9229: if ($gradingmechanism eq 'attendance') {
9230: $sum+=$pcorrect;
9231: } elsif ($correct[$i] eq '*') {
9232: $sum+=$pcorrect;
9233: } else {
9234: # We actually grade if correct or not
9235: my $increment=$pincorrect;
9236: # Special case: numerical answer "0"
9237: if ($correct[$i] eq '0') {
9238: if ($answer[$i]=~/^[0\.]+$/) {
9239: $increment=$pcorrect;
9240: }
9241: # General numerical answer, both evaluate to something non-zero
9242: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
9243: if (1.0*$correct[$i]==1.0*$answer[$i]) {
9244: $increment=$pcorrect;
9245: }
9246: # Must be just alphanumeric
9247: } elsif ($answer[$i] eq $correct[$i]) {
9248: $increment=$pcorrect;
9249: }
9250: $sum+=$increment;
9251: }
9252: }
9253: }
9254: my $ave=$sum/(100*$realnumber);
9255: # Store
9256: my ($username,$domain)=split(/\:/,$user);
9257: my %grades=();
9258: $grades{"resource.$part.solved"}='correct_by_override';
9259: $grades{"resource.$part.awarded"}=$ave;
9260: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
9261: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
9262: $env{'request.course.id'},
9263: $domain,$username);
9264: if ($returncode ne 'ok') {
9265: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
9266: } else {
9267: $storecount++;
9268: }
9269: }
9270: }
9271: # We are done
9272: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
9273: '</td>'.
9274: &Apache::loncommon::end_data_table_row().
9275: &Apache::loncommon::end_data_table();
9276: return $result;
9277: }
9278:
9279: sub navmap_errormsg {
9280: return '<div class="LC_error">'.
9281: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
9282: &mt('It is recommended that you [_1]re-initialize the course[_2] and then return to this grading page.','<a href="/adm/roles?selectrole=1&newrole='.$env{'request.role'}.'">','</a>').
9283: '</div>';
9284: }
9285:
9286: sub startpage {
9287: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
9288: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
9289: $r->print(&Apache::loncommon::start_page('Grading',undef,
9290: {'bread_crumbs' => $crumbs}));
9291: &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
9292: unless ($nodisplayflag) {
9293: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
9294: }
9295: }
9296:
9297: sub select_problem {
9298: my ($r)=@_;
9299: $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
9300: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
9301: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
9302: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
9303: }
9304:
9305: sub handler {
9306: my $request=$_[0];
9307: &reset_caches();
9308: if ($request->header_only) {
9309: &Apache::loncommon::content_type($request,'text/html');
9310: $request->send_http_header;
9311: return OK;
9312: }
9313: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
9314:
9315: &init_perm();
9316: if (!$env{'request.course.id'}) {
9317: # Not in a course.
9318: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
9319: return HTTP_NOT_ACCEPTABLE;
9320: } elsif (!%perm) {
9321: $request->internal_redirect('/adm/quickgrades');
9322: }
9323: &Apache::loncommon::content_type($request,'text/html');
9324: $request->send_http_header;
9325:
9326:
9327: # see what command we need to execute
9328:
9329: my @commands=&Apache::loncommon::get_env_multiple('form.command');
9330: my $command=$commands[0];
9331:
9332: if ($#commands > 0) {
9333: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
9334: }
9335:
9336: # see what the symb is
9337:
9338: my $symb=$env{'form.symb'};
9339: unless ($symb) {
9340: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9341: $symb=&Apache::lonnet::symbread($url);
9342: }
9343: &Apache::lonenc::check_decrypt(\$symb);
9344:
9345: $ssi_error = 0;
9346: if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
9347: #
9348: # Not called from a resource, but inside a course
9349: #
9350: &startpage($request,undef,[],1,1);
9351: &select_problem($request);
9352: } else {
9353: if ($command eq 'submission' && $perm{'vgr'}) {
9354: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
9355: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
9356: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
9357: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9358: {href=>'',text=>'Select student'}],1,1);
9359: &pickStudentPage($request,$symb);
9360: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
9361: &startpage($request,$symb,
9362: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9363: {href=>'',text=>'Select student'},
9364: {href=>'',text=>'Grade student'}],1,1);
9365: &displayPage($request,$symb);
9366: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
9367: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9368: {href=>'',text=>'Select student'},
9369: {href=>'',text=>'Grade student'},
9370: {href=>'',text=>'Store grades'}],1,1);
9371: &updateGradeByPage($request,$symb);
9372: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
9373: &startpage($request,$symb,[{href=>'',text=>'...'},
9374: {href=>'',text=>'Modify grades'}]);
9375: &processGroup($request,$symb);
9376: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
9377: &startpage($request,$symb);
9378: $request->print(&grading_menu($request,$symb));
9379: } elsif ($command eq 'individual' && $perm{'vgr'}) {
9380: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
9381: $request->print(&submit_options($request,$symb));
9382: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
9383: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
9384: $request->print(&listStudents($request,$symb,'graded'));
9385: } elsif ($command eq 'table' && $perm{'vgr'}) {
9386: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
9387: $request->print(&submit_options_table($request,$symb));
9388: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
9389: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
9390: $request->print(&submit_options_sequence($request,$symb));
9391: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
9392: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
9393: $request->print(&viewgrades($request,$symb));
9394: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
9395: &startpage($request,$symb,[{href=>'',text=>'...'},
9396: {href=>'',text=>'Store grades'}]);
9397: $request->print(&processHandGrade($request,$symb));
9398: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
9399: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
9400: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
9401: text=>"Modify grades"},
9402: {href=>'', text=>"Store grades"}]);
9403: $request->print(&editgrades($request,$symb));
9404: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
9405: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
9406: $request->print(&initialverifyreceipt($request,$symb));
9407: } elsif ($command eq 'verify' && $perm{'vgr'}) {
9408: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
9409: {href=>'',text=>'Verification Result'}]);
9410: $request->print(&verifyreceipt($request,$symb));
9411: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
9412: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
9413: $request->print(&process_clicker($request,$symb));
9414: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
9415: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9416: {href=>'', text=>'Process clicker file'}]);
9417: $request->print(&process_clicker_file($request,$symb));
9418: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
9419: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9420: {href=>'', text=>'Process clicker file'},
9421: {href=>'', text=>'Store grades'}]);
9422: $request->print(&assign_clicker_grades($request,$symb));
9423: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
9424: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9425: $request->print(&upcsvScores_form($request,$symb));
9426: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
9427: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9428: $request->print(&csvupload($request,$symb));
9429: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
9430: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9431: $request->print(&csvuploadmap($request,$symb));
9432: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
9433: if ($env{'form.associate'} ne 'Reverse Association') {
9434: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9435: $request->print(&csvuploadoptions($request,$symb));
9436: } else {
9437: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
9438: $env{'form.upfile_associate'} = 'reverse';
9439: } else {
9440: $env{'form.upfile_associate'} = 'forward';
9441: }
9442: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9443: $request->print(&csvuploadmap($request,$symb));
9444: }
9445: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
9446: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9447: $request->print(&csvuploadassign($request,$symb));
9448: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
9449: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9450: $request->print(&scantron_selectphase($request,undef,$symb));
9451: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
9452: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9453: $request->print(&scantron_do_warning($request,$symb));
9454: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
9455: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9456: $request->print(&scantron_validate_file($request,$symb));
9457: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
9458: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9459: $request->print(&scantron_process_students($request,$symb));
9460: } elsif ($command eq 'scantronupload' &&
9461: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9462: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9463: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9464: $request->print(&scantron_upload_scantron_data($request,$symb));
9465: } elsif ($command eq 'scantronupload_save' &&
9466: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9467: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9468: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9469: $request->print(&scantron_upload_scantron_data_save($request,$symb));
9470: } elsif ($command eq 'scantron_download' &&
9471: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
9472: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9473: $request->print(&scantron_download_scantron_data($request,$symb));
9474: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
9475: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9476: $request->print(&checkscantron_results($request,$symb));
9477: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
9478: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
9479: $request->print(&submit_options_download($request,$symb));
9480: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
9481: &startpage($request,$symb,
9482: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
9483: {href=>'', text=>'Download submissions'}]);
9484: &submit_download_link($request,$symb);
9485: } elsif ($command) {
9486: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
9487: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
9488: }
9489: }
9490: if ($ssi_error) {
9491: &ssi_print_error($request);
9492: }
9493: &Apache::lonquickgrades::endGradeScreen($request);
9494: $request->print(&Apache::loncommon::end_page());
9495: &reset_caches();
9496: return OK;
9497: }
9498:
9499: 1;
9500:
9501: __END__;
9502:
9503:
9504: =head1 NAME
9505:
9506: Apache::grades
9507:
9508: =head1 SYNOPSIS
9509:
9510: Handles the viewing of grades.
9511:
9512: This is part of the LearningOnline Network with CAPA project
9513: described at http://www.lon-capa.org.
9514:
9515: =head1 OVERVIEW
9516:
9517: Do an ssi with retries:
9518: While I'd love to factor out this with the vesrion in lonprintout,
9519: 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
9520: I'm not quite ready to invent (e.g. an ssi_with_retry object).
9521:
9522: At least the logic that drives this has been pulled out into loncommon.
9523:
9524:
9525:
9526: ssi_with_retries - Does the server side include of a resource.
9527: if the ssi call returns an error we'll retry it up to
9528: the number of times requested by the caller.
9529: If we still have a proble, no text is appended to the
9530: output and we set some global variables.
9531: to indicate to the caller an SSI error occurred.
9532: All of this is supposed to deal with the issues described
9533: in LonCAPA BZ 5631 see:
9534: http://bugs.lon-capa.org/show_bug.cgi?id=5631
9535: by informing the user that this happened.
9536:
9537: Parameters:
9538: resource - The resource to include. This is passed directly, without
9539: interpretation to lonnet::ssi.
9540: form - The form hash parameters that guide the interpretation of the resource
9541:
9542: retries - Number of retries allowed before giving up completely.
9543: Returns:
9544: On success, returns the rendered resource identified by the resource parameter.
9545: Side Effects:
9546: The following global variables can be set:
9547: ssi_error - If an unrecoverable error occurred this becomes true.
9548: It is up to the caller to initialize this to false
9549: if desired.
9550: ssi_error_resource - If an unrecoverable error occurred, this is the value
9551: of the resource that could not be rendered by the ssi
9552: call.
9553: ssi_error_message - The error string fetched from the ssi response
9554: in the event of an error.
9555:
9556:
9557: =head1 HANDLER SUBROUTINE
9558:
9559: ssi_with_retries()
9560:
9561: =head1 SUBROUTINES
9562:
9563: =over
9564:
9565: =item scantron_get_correction() :
9566:
9567: Builds the interface screen to interact with the operator to fix a
9568: specific error condition in a specific scanline
9569:
9570: Arguments:
9571: $r - Apache request object
9572: $i - number of the current scanline
9573: $scan_record - hash ref as returned from &scantron_parse_scanline()
9574: $scan_config - hash ref as returned from &get_scantron_config()
9575: $line - full contents of the current scanline
9576: $error - error condition, valid values are
9577: 'incorrectCODE', 'duplicateCODE',
9578: 'doublebubble', 'missingbubble',
9579: 'duplicateID', 'incorrectID'
9580: $arg - extra information needed
9581: For errors:
9582: - duplicateID - paper number that this studentID was seen before on
9583: - duplicateCODE - array ref of the paper numbers this CODE was
9584: seen on before
9585: - incorrectCODE - current incorrect CODE
9586: - doublebubble - array ref of the bubble lines that have double
9587: bubble errors
9588: - missingbubble - array ref of the bubble lines that have missing
9589: bubble errors
9590:
9591: =item scantron_get_maxbubble() :
9592:
9593: Arguments:
9594: $nav_error - Reference to scalar which is a flag to indicate a
9595: failure to retrieve a navmap object.
9596: if $nav_error is set to 1 by scantron_get_maxbubble(), the
9597: calling routine should trap the error condition and display the warning
9598: found in &navmap_errormsg().
9599:
9600: $scantron_config - Reference to bubblesheet format configuration hash.
9601:
9602: Returns the maximum number of bubble lines that are expected to
9603: occur. Does this by walking the selected sequence rendering the
9604: resource and then checking &Apache::lonxml::get_problem_counter()
9605: for what the current value of the problem counter is.
9606:
9607: Caches the results to $env{'form.scantron_maxbubble'},
9608: $env{'form.scantron.bubble_lines.n'},
9609: $env{'form.scantron.first_bubble_line.n'} and
9610: $env{"form.scantron.sub_bubblelines.n"}
9611: which are the total number of bubble, lines, the number of bubble
9612: lines for response n and number of the first bubble line for response n,
9613: and a comma separated list of numbers of bubble lines for sub-questions
9614: (for optionresponse, matchresponse, and rankresponse items), for response n.
9615:
9616:
9617: =item scantron_validate_missingbubbles() :
9618:
9619: Validates all scanlines in the selected file to not have any
9620: answers that don't have bubbles that have not been verified
9621: to be bubble free.
9622:
9623: =item scantron_process_students() :
9624:
9625: Routine that does the actual grading of the bubble sheet information.
9626:
9627: The parsed scanline hash is added to %env
9628:
9629: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
9630: foreach resource , with the form data of
9631:
9632: 'submitted' =>'scantron'
9633: 'grade_target' =>'grade',
9634: 'grade_username'=> username of student
9635: 'grade_domain' => domain of student
9636: 'grade_courseid'=> of course
9637: 'grade_symb' => symb of resource to grade
9638:
9639: This triggers a grading pass. The problem grading code takes care
9640: of converting the bubbled letter information (now in %env) into a
9641: valid submission.
9642:
9643: =item scantron_upload_scantron_data() :
9644:
9645: Creates the screen for adding a new bubble sheet data file to a course.
9646:
9647: =item scantron_upload_scantron_data_save() :
9648:
9649: Adds a provided bubble information data file to the course if user
9650: has the correct privileges to do so.
9651:
9652: =item valid_file() :
9653:
9654: Validates that the requested bubble data file exists in the course.
9655:
9656: =item scantron_download_scantron_data() :
9657:
9658: Shows a list of the three internal files (original, corrected,
9659: skipped) for a specific bubble sheet data file that exists in the
9660: course.
9661:
9662: =item scantron_validate_ID() :
9663:
9664: Validates all scanlines in the selected file to not have any
9665: invalid or underspecified student/employee IDs
9666:
9667: =item navmap_errormsg() :
9668:
9669: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
9670: Should be called whenever the request to instantiate a navmap object fails.
9671:
9672: =back
9673:
9674: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>